c# - 异步套接字客户端 ReceiveCallback 未执行

标签 c# sockets c#-4.0 tcpclient beginreceive

您好,我正在使用以下示例代码开发 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());
        }
    }

上下文:该应用程序是直流电动扭矩工具 Controller 的接口(interface)。我连接到 Controller 的 IP 地址和端口 4545,而不是能够发送开放协议(protocol)命令来更改设置。

最佳答案

解决方案位于 https://social.msdn.microsoft.com/Forums/vstudio/en-US/05dcda20-06f9-419b-bfc0-bcb8cfeb3693/socket-receivecallback-not-sending-notification-when-buffer-has-emptied?forum=csharpgeneral

这是我的修复代码。请检查“添加到修复”部分。

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));
            }                                                       // Add to fix
                                                                    // Add to fix
            int bytesRemain = state.workSocket.Available;           // Add to fix
            if (bytesRemain>0)                                      // Add to fix
            {                                                       // Add to fix
                //  Get the rest of the data.  
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.  

                if (state.sb.Length >= 1)                 //<-- Fixed from>1 to >=1
                    response = state.sb.ToString();
                else
                    response = ""; //OR null;

                // Signal that all bytes have been received.  
                receiveDone.Set();
            }
        }

以下是我对为什么原版不能工作的分析:
  • 我向服务器发送一条消息,例如“*IDN?”。服务器回复了34个字母的消息,如“仪器ABC,xx,xx,xx”。 ReceiveCallBack 已成功读取它。所以 bytesRead = 34。
  • 但是有一个检查说如果 bytesRead > 0,可能是,只是可能那里仍然有数据,所以 ReceiveCallBack 本身启动了一个新的客户端。再次开始接收。
  • 但这一次,没有来自服务器的数据。所以客户端等待,等待,等待,ReceiveCallBack 再也没有被回调......
  • 所以 ReceiveCallBack 的 else-branch 永远不会被执行。因此,“response”变量从未设置,receiveDone 也从未设置。
  • 关于c# - 异步套接字客户端 ReceiveCallback 未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047625/

    相关文章:

    .net - 在类库项目中缺少 "System.ServiceModel"

    android - 将 Android 可穿戴模拟器与连接到 adb 的手持设备无线连接

    wpf - 如果安装了AVG防病毒软件,下载失败

    c# - 自定义通用用户控件未出现在工具箱中

    c# - 用于对我无法轻松创建的返回类型进行单元测试的选项

    java.io.StreamCorruptedException : invalid stream header: FAD08000

    python-3.x - 如何将套接字消息转换为字符串消息

    c#-4.0 - Cloud 9 是否支持 .Net 进行构建、部署或调试?

    c# - 对于高可伸缩性和性能需求,在 PHP 应用程序的后端使用 C++ 还是 Java 实现更可取?

    c# - 防止用户切换到其他窗口