客户端未及时收到消息(TcpClient)

时间:2015-07-08 13:18:57

标签: c# sockets tcpclient

我有两个应用程序" talk"通过Tcp相互之间的问题是,当我发送某些内容时,应用程序并不会同时收到它,只有当他第二次请求时才会收到,然后“他”才会发送内容。接收它重复。例如:

客户请求连接(收入字符串: 00200001 0050 );

服务器接受连接(确认)(输出字符串: 00570002 );

客户端没有收到确认,但当他再次请求连接时,它会收到一个输出字符串: 00570002 00570002 (重复)。

这种情况发生在连接到我的任何应用程序中。

            private int listenerPort = 4545;
            private TcpListener listener;
            private TcpClient socket;

            public Communicator()
            {
                try
                {
                    this.listener = new TcpListener(IPAddress.Parse("127.0.0.1"), listenerPort);
                    listenerPort++;
                    listener.Start();
                    this.connectToPendingRequest();
                }
                catch (Exception ex)
                {
                    listener.Stop();
                    throw new Exception(ex.Message);
                }
            }

            /// <summary>
            /// Try to connect to any pending requests
            /// </summary>
            public void connectToPendingRequest()
            {
                try
                {
                    if (socket == null || !socket.Connected)
                        if (listener.Pending())
                        {
                            this.socket = Listener.AcceptTcpClient();
                            this.socket.NoDelay = true;
                        }
                }
                catch (InvalidOperationException) { throw new Exception("Listener was not started!"); }
                catch (Exception ex) { throw new Exception("Error has ocurred when connecting to device: " + ex.Message); }
            }

            /// <summary>
            /// Send messages to Device
            /// </summary>
            public void sendMessages(string stringMessage)
            {
                if (socket.Connected)
                {
                    try
                    {
                        byte[] outStream = Encoding.ASCII.GetBytes(stringMessage);
                        socket.GetStream().Write(outStream, 0, outStream.Length);
                        socket.GetStream().Flush();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Message could not be sent.\nError: " + ex.Message);
                    }

                }
                else { throw new Exception("No device connected"); }

            }

        /// <summary>
        /// Get Message From socket
        /// </summary>
        /// <returns></returns>
        public String getMessageFromSocket()
        {
            try
            {
                byte[] inStream = new byte[10025];

                socket.GetStream().Read(inStream, 0, (int)socket.ReceiveBufferSize);
                return System.Text.Encoding.ASCII.GetString(inStream);
            }
            catch (Exception ex)
            {
                throw new Exception("Message could not be read.\nError: " + ex.Message);
            }
        }

我忘记了什么吗?它有办法确保消息到达吗? (猜猜tcp应该这样做但是......)

Ps:接收消息时我没有遇到任何问题。

提前致谢!

2 个答案:

答案 0 :(得分:1)

  1. listenerPort++;不需要。多个客户端可以连接到同一端口上的同一个侦听器
  2. 我在这里看不到客户端代码,或者它与服务器代码纠缠在一起
  3. socket.GetStream()。不需要Flush()。
  4. .Pending()是非阻塞的,因此您可以错过连接时刻
  5. 查看TcpListenerTcpClient代码示例

答案 1 :(得分:0)

以下是使用Read()返回值的快速示例:

    /// <summary>
    /// Get Message From socket
    /// </summary>
    /// <returns></returns>
    public String getMessageFromSocket()
    {
        try
        {
            byte[] inStream = new byte[10025];

            int bytesRead = socket.GetStream().Read(inStream, 0, inStream.Length);
            return System.Text.Encoding.ASCII.GetString(inStream, 0, bytesRead);
        }
        catch (Exception ex)
        {
            throw new Exception("Message could not be read.\nError: " + ex.Message);
        }
    }

不要忽视Scott Chamberlain给你的伟大建议。这对于确定何时收到完整的“消息”的更大问题根本没有帮助。