您好,我正在使用以下示例代码开发 C# Winforms 应用程序:
https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx
它连接到正确的 IP 地址和端口号,但在发送字符串命令并等待响应后,应用程序卡住了,因为 ReceiveCallback 没有被执行,因此没有设置 receiveDone ManualResetEvent。我 100% 确定我想收到回复,但应用程序只是卡住并且不执行 ReceiveCallback 方法。没有执行 ReceiveCallback 方法的可能原因是什么?
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());
}
}
上下文:该应用程序是直流电动扭矩工具控制器的接口。我连接到控制器的 IP 地址和端口 4545,而不是能够发送开放协议命令来更改设置。