2014-09-23 63 views
1

我想做异步套接字通信,并希望服务器保持所有连接的套接字列表,以便他可以向他们广播消息。异步套接字 - 与C#中的永久套接字双工通信

首先我从msdn Asynchronous Socket Server的例子中改变它们,使它们不关闭套接字。 (刚刚删除了.shutdown和.Close命令)

但这样做似乎导致客户端挂在“接收部分”。

这里是我的MSDN例子所做的更改:

客户:

不仅改变ReceiveCallback(),使其保持在一个无限接收循环:

private static void ReceiveCallback(IAsyncResult ar) 
{ 
    try 
    { 
     // Retrieve the state object and the client socket 
     // from the asynchronous state object. 
     StateObject state = (StateObject)ar.AsyncState; 
     Socket client = state.workSocket; 

     // Read data from the remote device. 
     int bytesRead = client.EndReceive(ar); 

     if (bytesRead > 0) 
     { 
      // There might be more data, so store the data received so far. 
      state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); 

      // Get the rest of the data. 
      client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
       new AsyncCallback(ReceiveCallback), state); 
     } 
     else 
     { 
      // All the data has arrived; put it in response. 
      if (state.sb.Length > 1) 
      { 
       response = state.sb.ToString(); 
       Console.WriteLine(state.sb.ToString()); 
      } 
      // Signal that all bytes have been received. 
      receiveDone.Set(); 

      // Get the rest of the data. 
      client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
       new AsyncCallback(ReceiveCallback), state); 
     } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 
} 

服务器: 刚刚评论过关闭插座的线路:

//handler.Shutdown(SocketShutdown.Both); 
//handler.Close(); 

后来我计划保留一个套接字列表,这样我就可以向他们发送消息,但它已经在这里失败了。

我对任何提示都很满意,我也希望听到您对使用此tenique用于服务器的意见,该服务器必须服务于最多100个客户端,这可能会在任何2秒钟内发送请求。 (通信应该是两种方式,以便客户端和服务器可以随时发送消息,而无需等待消息响应)。

谢谢你,晚上好 马丁

回答

1

EndReceive只有当关闭套接字返回0。您的客户永远不会设置receiveDone句柄,因为服务器从不关闭套接字。回调在接收数据或连接终止时被调用。

你需要检测消息的结尾(就像你链接的例子一样)。 例如。 (您链接的代码的修改版)

content = state.sb.ToString(); 
if (content.IndexOf("<EOF>") > -1) { 
    // All the data has been read from the 
    // client. Display it on the console. 
    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", 
       content.Length, content); 
    // Echo the data back to the client. 
    Send(handler, content); 

    { // NEW 
     // Reset your state (persist any data that was from the next message?)  

     // Wait for the next message. 
     handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
     new AsyncCallback(ReadCallback), state); 
    } 

} else { 
     // Not all data received. Get more. 
     handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
     new AsyncCallback(ReadCallback), state); 
} 
+0

您好,非常感谢您的帮助。检查EndOfMessage Singal()解决了该问题。 – 2014-09-24 18:48:19