c# tcp异步连接

2020-02-13 10:20:02 浏览数 (1)

服务端

代码语言:javascript复制
public NetTcpServer(string ip,int port, SensorType type)
{//启动监听
     m_ServerConnecType = type;
     m_listen = new TcpListener(IPAddress.Parse(ip), port);
     m_listen.Start();
     m_listen.BeginAcceptTcpClient(AcceptTcpClient, m_listen);  //接收连接
}
代码语言:javascript复制
private void AcceptTcpClient(IAsyncResult ar)
{//建立连接
    TcpClient recClient = m_listen.EndAcceptTcpClient(ar);
    try{
        if(envSetWindowsData!=null)    envSetWindowsData(DataType.NetConnected, ClassByteConvert.Class2Byte(recClient.Client.LocalEndPoint));
        m_listen.BeginAcceptTcpClient(AcceptTcpClient, m_listen);
        Task.Run(new Action(() => {//接收线程
        	byte[] recData = new byte[1024];//不要用成员变量,异步不能只有一个缓冲区
	        recClient.Client.BeginReceive(recData, 0, recData.Length, SocketFlags.None, RecieveDataAsyn, recClient);//接收连接
        }));//两个异步函数不能在一个线程中执行
        Task.Run(new Action(() => {//发送线程
            if (envSetWindowsData != null)

0 人点赞