Socket实现异步通信

时间:2022-10-16 21:19:20

Socket实现异步通信Socket实现异步通信Socket实现异步通信

private static void RecVing(IAsyncResult Result)

{
    //通过 result 获取socket。在这个socket上你启动了BeginAccept操作
    Socket socket = Result.AsyncState as Socket;
 
    Socket Res_soc = null; //这个是与当前客户端连接的Socket
    Socket_Business business = new Socket_Business(); 
    try
    {
        // 通过EndAccept,获取与当前客户端连接的Socket
         Res_soc  = socket.EndAccept(Result);
        Console.WriteLine("连接成功!");
        byte[] bytes =new byte[80];
        int i = Res_soc.Receive(bytes);
        string cmdstr = System.Encoding.Default.GetString(bytes, 0, i);
        Console.WriteLine(cmdstr);  
        business.Business(bytes, Res_soc);
        send(Res_soc);
     }
     catch 
     {
         // 发生异常时,释放Res_soc
         if(Res_soc != null) Res_soc = null;
      }
     finally  //利用finally 确保无论发生什么异常都能够让socket继续接收连接
     {
         //继续异步等待连接
         socket.BeginAccept(new AsyncCallback(RecVing), socket);
     }             
}