2014-09-23 62 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