我創建了一個異步服務器,可以從任意數量的客戶端讀取消息。我的服務器代碼與此示例密切相關:http://msdn.microsoft.com/en-us/library/fx6588te.aspx定期將數據從服務器發送到客戶端
客戶端連接後,我想定期向該客戶端發送數據,可能每秒鐘發送2到3次。我想不出用異步send()實現這一點的好方法。我假設某種計時機制需要添加到我的AcceptCallback()
方法中,因爲這是與客戶端的連接發生的地方。
在以前的版本我的服務器我用阻止套接字,只是我的環法send()
在一個無限循環while()
叫sleep()
得到的時機了。
這裏就是我想:
public void AcceptCallback(IAsyncResult ar)
{
allDone.Set(); // Signal the main thread to continue.
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
IPEndPoint remotePoint = (IPEndPoint)handler.RemoteEndPoint;
IPAddress remoteAddress = remotePoint.Address;
Console.WriteLine("Connected to {0}!", remoteAddress.ToString());
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
//Start periodically sending here??
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
只需在'Timer'開始'BackgroundWorker'線程的工作即可。 – 2012-07-13 15:49:46