我想做異步套接字通信,並希望服務器保持所有連接的套接字列表,以便他可以向他們廣播消息。異步套接字 - 與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秒鐘內發送請求。 (通信應該是兩種方式,以便客戶端和服務器可以隨時發送消息,而無需等待消息響應)。
謝謝你,晚上好 馬丁
您好,非常感謝您的幫助。檢查EndOfMessage Singal()解決了該問題。 –
2014-09-24 18:48:19