【问题标题】:TCP response cut shortTCP 响应缩短
【发布时间】:2012-11-18 20:42:36
【问题描述】:

我在 WP7 中使用 TCP 客户端。目前我只是使用来自 MSDN 的示例代码,所以它应该可以工作。但由于某种原因,这种特殊的反应被缩短了。

它应该回复(后跟大量空字节,来自缓冲区):

202- 多行响应如下\r\ntimestamp=0x00000000 checksum=0x00000000\r\nname=\"FLASH:Flash\xshell.xex\"\r\n.\r\n

但它反而返回(并且没有任何尾随空字节):

202- 多行响应如下\r\n

我从 TCP 服务器获取响应的代码是:

        try
        {
            if (!_isConnected)
                Connect();
            if (!_isConnected)
                return null;

            SendTextCommand(command);

            string response = "";

            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
            socketEventArg.UserToken = null;

            socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                    response = Encoding.ASCII.GetString(e.Buffer);
                    response = response.Trim('\0');
                }
                else
                    throw new Exception(e.SocketError.ToString());

                _pausingThread.Set();
            });

            _pausingThread.Reset();
            _socket.ReceiveAsync(socketEventArg);
            _pausingThread.WaitOne(TIMEOUT_MILLISECONDS);

            return response;
        }
        catch (Exception ex) { GenerateException(ex.Message); return "123"; }

【问题讨论】:

  • 我不确定,但我认为有时缓冲区在您读取之前不会保存所有数据。尝试使用 Thread.Sleep(100);或稍等片刻,看看它是否会有完整的字符串。还有,MAX_BUFFER_SIZE是多少,够吗?
  • 是的,如果我再次调用该函数,它会返回更多的输出字符串。而 MAX_BUFFER_SIZE 是 (3 * 1024),所以足够大了。您建议将 Thread.Sleep 放在哪里?
  • 在读取缓冲区之前将其放在 if (e.SocketError == SocketError.Success) 之后,我知道这是一个糟糕的解决方案,但您无法控制网络速度和其他协议栈的层。这种情况一直在发生,因此您必须针对这种情况调整程序逻辑(即在字符串末尾添加一些特殊字符,从而在 TCP/IP 协议之上实现您自己的协议)。
  • 你试过了吗?有用吗?
  • 我的一个朋友告诉我循环播放,直到整个消息都送达。因为 TCP 连接不像流。我将在上面发布工作代码。

标签: c# windows-phone-7 networking tcp


【解决方案1】:

要修复它,您必须检查响应是否是多行的。如果是,则循环直到它以“.\r\n”结束。否则你读一次就完成了。像这样:

public string GetFromTextCommand(string command)
    {
        try
        {
            if (!_isConnected)
                Connect();
            if (!_isConnected)
                return null;

            SendTextCommand(command);

            string response = GetFromTextCommand();

            if (response.StartsWith("202"))
            {
                while (!response.EndsWith(".\r\n"))
                {
                    string newResponse = GetFromTextCommand();

                    response += newResponse;
                }
            }

            return response;
        }
        catch (Exception ex) { GenerateException(ex.Message); return null; }
    }
    public string GetFromTextCommand()
    {
        try
        {
            if (!_isConnected)
                Connect();
            if (!_isConnected)
                return null;

            string response = "";

            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
            socketEventArg.UserToken = null;

            socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                    response = Encoding.ASCII.GetString(e.Buffer);
                    response = response.Trim('\0');
                }
                else
                    throw new Exception(e.SocketError.ToString());

                _pausingThread.Set();
            });

            _pausingThread.Reset();
            _socket.ReceiveAsync(socketEventArg);
            _pausingThread.WaitOne(TIMEOUT_MILLISECONDS);

            return response;
        }
        catch (Exception ex) { GenerateException(ex.Message); return null; }
    }

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多