对Socket beginreceive的异步接收回调函数有点疑问
请问下,关于那个socket的异步接收回调,为什么当bytesRead < StateObject.BufferSize的时候,只运行一次?
分值不多,还望高手慷慨赐教,谢!
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. bytesRead < StateObject.BufferSize的时候这句就没运行过,然后就无法继续了,因为receiveDone.Set();无法执行
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());
}
}
分值不多,还望高手慷慨赐教,谢!
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. bytesRead < StateObject.BufferSize的时候这句就没运行过,然后就无法继续了,因为receiveDone.Set();无法执行
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());
}
}
...全文
相关推荐
socket异步利用BeginReceive
大半夜的爬起来给别人写的个socket的异步示例,里面有很多缺陷,但是懒得改了,只是演示程序而已,本程序包含server和client2部分,客户端主动连接服务器,建立连接后,客户端可以给服务器发文本消息,服务器也可以给客户端发,非常简单的一个小程序,备忘。
C# 基于socket实现的异步TcpServer和TcpClient
C#编写的TCP异步通信,采用Socket实现,(还可用C#对Socket的封装TcpClient和TcpListener实现) 包含服务端及客户端完整代码
C#socket异步发送与接收类
实现SOCKET异步网络传输 包含发送、接收、事件
Socket异步接收、调试
可用于Socket异步接收和报文调试,使用C#开发,运行需要.Net Framework库。
C#socketUdp异步消息发送接收
C# socketUdp 异步 消息发送接收


