首页 文章

我无法通过socket.receive接收服务器完整响应

提问于
浏览
0

我用socket.send向服务器发送命令,服务器响应我但我无法收到完整的响应 . 缓冲区大小小吗?问题出在哪儿?!!

private void send(string toSend)
        {
            byte[] data = new byte[8192];
            int dataLenght = 0;
            string ServerResponse = "";
            try
            {

                data = Encoding.ASCII.GetBytes(toSend);
                sock.Send(data);
                data = new byte[8192];
                dataLenght = 0;

                   while (sock.Available != 0)
                    {
                     //   System.Threading.Thread.Sleep(200);
                        data = new byte[8192];
                        dataLenght = 0;
                        dataLenght = sock.Receive(data);
                        ServerResponse += Encoding.ASCII.GetString(data, 0, dataLenght);
                    }

                    txtResponse.Text += toSend + ServerResponse + "\n";
                    txtResponse.SelectionStart = txtResponse.TextLength;
                    txtResponse.ScrollToCaret();

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
            }
        }

1 回答

  • 1

    这里的问题是使用 Socket.Available 作为消息测试的结束 . 's not what it is, and it'不是它的用途 . 在您拥有完整的消息之前,您需要继续阅读,无论您的协议中有什么意义 . TCP中没有任何内容可以帮助您 . 它只是一个字节 - 蒸汽协议 .

相关问题