新书推介:《语义网技术体系》
作者:瞿裕忠,胡伟,程龚
   XML论坛     W3CHINA.ORG讨论区     计算机科学论坛     SOAChina论坛     Blog     开放翻译计划     新浪微博  
 
  • 首页
  • 登录
  • 注册
  • 软件下载
  • 资料下载
  • 核心成员
  • 帮助
  •   Add to Google

    >> 本版讨论.NET,C#,ASP,VB技术
    [返回] 中文XML论坛 - 专业的XML技术讨论区计算机技术与应用『 Dot NET,C#,ASP,VB 』 → .NET TCP异步操作的类 查看新帖用户列表

      发表一个新主题  发表一个新投票  回复主题  (订阅本版) 您是本帖的第 6651 个阅读者浏览上一篇主题  刷新本主题   树形显示贴子 浏览下一篇主题
     * 贴子主题: .NET TCP异步操作的类 举报  打印  推荐  IE收藏夹 
       本主题类别:     
     卷积内核 帅哥哟,离线,有人找我吗?
      
      
      威望:8
      头衔:总统
      等级:博士二年级(版主)
      文章:3942
      积分:27590
      门派:XML.ORG.CN
      注册:2004/7/21

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给卷积内核发送一个短消息 把卷积内核加入好友 查看卷积内核的个人资料 搜索卷积内核在『 Dot NET,C#,ASP,VB 』的所有贴子 访问卷积内核的主页 引用回复这个贴子 回复这个贴子 查看卷积内核的博客楼主
    发贴心情 .NET TCP异步操作的类


    分成两部分 一部分是服务 一部分是客户

    全部代码using System;   
    using System.Threading;   
    using System.Net;   
    using System.Net.Sockets;   
    using System.Collections;   
      
      
    namespace Zgke.Net   
    {   
        /// <summary>   
        /// Tcp的异步操作   
        /// zgke@sina.com   
        /// </summary>   
        public class Tcp   
        {   
            public class TcpClient   
            {  
                #region 变量   
                /// <summary>   
                /// 端口号   
                /// </summary>   
                private int port = 8000;   
                /// <summary>   
                /// IP地址   
                /// </summary>   
                private IPAddress ip;  


                #endregion  

                #region 委托   
                /// <summary>   
                /// 接受数据   
                /// </summary>   
                public delegate void ReadByte(byte[] ReadByte);   
                public event ReadByte ReadBytes;  
                #endregion   
      
                public TcpClient(string IP, int Port)   
                {   
                    if (Port != 0) port = Port;   
                    if (IP != "") ip = IPAddress.Parse(IP);   
                }   
      
                /// <summary>   
                /// 反送消息   
                /// </summary>   
                /// <param name="SendByte">需要发送的数据</param>   
                public void SendByte(byte[] SendByte, bool Close)   
                {   
                    Socket socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);  //建立SOCKET   
                    IPEndPoint ipendpoint = new IPEndPoint(ip, port);  //建立IP目标和端口   
                    socket.Connect(ipendpoint);//连接   
      
                    socket.BeginSend(SendByte, 0, SendByte.Length, SocketFlags.None, null, socket); //发送数据   
      
                    if (Close == true)   
                    {   
                        socket.Close();   
                        return;   
                    }   
                    byte[] temp = new byte[1]; //建立个临时的发送数据   
                    socket.BeginReceive(temp, 0, 0, SocketFlags.None, new AsyncCallback(Read), socket);  //建立异步读取                          
                }  

                #region 私有方法   
                private void Read(IAsyncResult iar)   
                {   
                    Socket socket = (Socket)iar.AsyncState; //获取Socket对象   
      
                    int ReadCount = socket.Available;  //获得包大小   
                    if (ReadCount == 0) return;  //如果包是0 就直接返回   
                    byte[] Byte = new byte[ReadCount];   //建立要接收的对象信息   
                    socket.BeginReceive(Byte, 0, ReadCount, SocketFlags.None, null, socket); //开始读取   
                    if (ReadBytes != null) ReadBytes(Byte);  //执行委托   
      
                }  


                #endregion   
            }   
      
            public class TcpServer   
            {   
                /// <summary>   
                /// 保存监听   
                /// </summary>   
                private Socket listener;   
                /// <summary>   
                /// 端口号   
                /// </summary>   
                private int TcpPort = 8000;   
                /// <summary>   
                /// IP地址   
                /// </summary>   
                private string TcpIP = "127.0.0.1";   
      
      
                /// <summary>   
                /// 默认地址池   
                /// </summary>   
                private int Bocklog = 10;   
      
      
                /// <summary>   
                /// 关闭标志   
                /// </summary>   
                private bool ServerRunTCP = false;   
      
                /// <summary>   
                /// 服务器运行状态   
                /// </summary>   
                public bool ServerRun   
                {   
                    get { return ServerRunTCP; }   
                }   
      
      
                /// <summary>   
                /// 执行消息   
                /// </summary>   
                public delegate void MessageText(string MessageText);   
                public event MessageText Message;   
      
                /// <summary>   
                /// 读写数据   
                /// </summary>   
                public delegate void ReadByte(byte[] ReadByte, ref byte[] SendByte, ref bool Close);   
                public event ReadByte ReadBytes;   
      
      
      
      
                public TcpServer(string IP, int Port)   
                {   
                    if (Port > 1) TcpPort = Port;   
                    if (IP != "") TcpIP = IP;   
                }   
      
                public void Star()   
                {   
                    if (ServerRun == true)   
                    {   
                        Message("Server Runling....");   
                        return;   
                    }   
      
                    listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
      
                    listener.Bind(new IPEndPoint(IPAddress.Parse(TcpIP), TcpPort));   
      
                    listener.Listen(Bocklog);   
      
                    listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);   
                    ServerRunTCP = true;   
                }   
      
                public void Close()   
                {   
                    if (ServerRun == false)   
                    {   
                        Message("Server Not Run");   
                        return;   
                    }   
                    ServerRunTCP = false;   
                    listener.Close();   
                }  


                #region 私有方法   
                private void OnConnectRequest(IAsyncResult ar)   
                {   
                    if (ServerRunTCP == false) return;   
                    Socket listener = (Socket)ar.AsyncState;   
                    Socket sock = listener.EndAccept(ar);   
      
      
                    listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);   
      
      
      
      
                    if (Message != null) Message(sock.RemoteEndPoint.ToString() + " Join");   
      
      
                    byte[] temp = new byte[0];   
                    sock.BeginReceive(temp, 0, 0, SocketFlags.None, new AsyncCallback(OnRecievedData), sock);   
      
                }   
                private void OnRecievedData(IAsyncResult ar)   
                {   
      
                    Socket sock = (Socket)ar.AsyncState;   
      
                    if (ServerRunTCP == false)   
                    {   
                        sock.Close();   
                        return;   
                    }   
      
      
                    int RecievedSize = sock.Available;   
      
      
      
                    if (RecievedSize == 0)   
                    {   
                        if (Message != null) Message(sock.RemoteEndPoint.ToString() + " Close");   
                        sock.Close();   
      
                        return;   
                    }   
      
                    byte[] RecievedData = new byte[RecievedSize];   
      
                    sock.Receive(RecievedData);   
      
      
                    if (Message != null) Message(sock.RemoteEndPoint.ToString() + " Read " + RecievedSize.ToString());   
      
                    byte[] SendData = new byte[0];   
                    bool CloseSock = false;   
                    if (ReadBytes != null) ReadBytes(RecievedData, ref SendData, ref CloseSock);   
      
                    if (SendData.Length != 0) sock.BeginSend(SendData, 0, SendData.Length, SocketFlags.None, null, sock);   
      
      
                    if (CloseSock == true)   
                    {   
                        sock.Close();   
                        return;   
                    }   
                    RecievedData = new byte[0];   
      
                    sock.BeginReceive(RecievedData, 0, 0, SocketFlags.None, new AsyncCallback(OnRecievedData), sock);   
      
                }  

                #endregion   
      
            }   
      
      
        }   
    }


       收藏   分享  
    顶(0)
      




    ----------------------------------------------
    事业是国家的,荣誉是单位的,成绩是领导的,工资是老婆的,财产是孩子的,错误是自己的。

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2012/7/24 10:14:00
     
     GoogleAdSense
      
      
      等级:大一新生
      文章:1
      积分:50
      门派:无门无派
      院校:未填写
      注册:2007-01-01
    给Google AdSense发送一个短消息 把Google AdSense加入好友 查看Google AdSense的个人资料 搜索Google AdSense在『 Dot NET,C#,ASP,VB 』的所有贴子 访问Google AdSense的主页 引用回复这个贴子 回复这个贴子 查看Google AdSense的博客广告
    2024/12/27 2:38:19

    本主题贴数1,分页: [1]

    管理选项修改tag | 锁定 | 解锁 | 提升 | 删除 | 移动 | 固顶 | 总固顶 | 奖励 | 惩罚 | 发布公告
    W3C Contributing Supporter! W 3 C h i n a ( since 2003 ) 旗 下 站 点
    苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
    83.008ms