我只是想用一个小的内部套接字客户端/服务器做一个概念验证。我只是传递一个字符串,将收到一个特定的字符串。例如发送 - > “UCME”接收 - >“ICU”
我一直关注MSDN示例Async Example,并且Synchronous Client按预期工作。但是我实际上想要没有的异步客户端。它结束当前ReceiveCallback
,然后无限期挂起。我没有得到错误,没有。唯一的线索是我在F10(ing)退出
Step into: Stepping over non-user code 'System.Net.LazyAsyncResult.Complete'
Step into: Stepping over non-user code 'System.Threading.ExecutionContext.Run'
Step into: Stepping over non-user code 'System.Threading._IOCompletionCallback.PerformIOCompletionCallback'
有什么想法吗?
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
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.
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());
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}