服务器的BeginRead部分是这样的:
private void listen()
{
allDone.Reset();
networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(newDataRecievedCallback), null);
allDone.WaitOne(10);
}
private void newDataRecievedCallback(IAsyncResult rst)
{
try
{
int incomeDataSize = networkStream.EndRead(rst);
lastRecievedBuffer = convertToString(buffer, incomeDataSize).Trim();
cleanBuffer();
if (IsValidXml(lastRecievedBuffer))
parseXML(lastRecievedBuffer);
allDone.Set();
//Here I call the listen() method again
listen();
}
catch (Exception ex)
{
LogSystem.saveServerError(ex.StackTrace, ex.Source);
}
}
NetworkStream的用法:
private NetworkStream networkStream;
private TcpClient tcpClient;
//this part is in the constructor of the Server class
tcpClient = new TcpClient(loginData.Host, loginData.Port);
networkStream = tcpClient.GetStream();
这是BeginRead()的正确用法还是我像同步逻辑一样调用Async BeginRead()方法?
有没有更好的方法来再次调用listen()方法呢? 谢谢!