例子程序http://msdn.microsoft.com/zh-cn/library/bew39x2a(v=VS.80).aspx
我贴出其中的接收回调函数的代码
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();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}那个else语句根本是执行不到的,这个算是bug吗?算是误导吗?
如果不是,
那为什么要这么写呢?
高手指点下
要是我想在异步数据接收完成时给用户一个提示的话
怎么知道接收完成了呢?
说那个定义协议的先停停,先不说根据发送协议头来判断数据长度,说说其他说法
我贴出其中的接收回调函数的代码
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();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}那个else语句根本是执行不到的,这个算是bug吗?算是误导吗?
如果不是,
那为什么要这么写呢?
高手指点下
要是我想在异步数据接收完成时给用户一个提示的话
怎么知道接收完成了呢?
说那个定义协议的先停停,先不说根据发送协议头来判断数据长度,说说其他说法
这个else还是执行不到
那这个else到底是什么时候执行到呢?