Do I have to create a new TcpClient for each message I send?

佐手、 提交于 2019-12-12 01:38:23

问题


I remain frustrated in my attempts to send multiple TCP messages. I do not know what I have to do on the client side. I've tried using a Socket object and a TcpClient object. I can send one message with no problem. But what do I have to do to send a second message? Do I have to just discard the socket or TcpClient and create a new one? I've never yet been able to to get a second message to work.

Here is my latest attempt with TcpClient. It sends one message and displays the response successfully. But when I put a breakpoint on the first statement inside the while loop and look at the client object before sending the second message, I see that the client's Connected property is false. But on the next line, when I try to call Connect(), an exception is thrown claiming that the object is already connected.

Could somebody please explain what's going on, and what I have to do?

        TcpClient client = new TcpClient();

        while (true)
        {

            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes("This message came from the client.");

            client.Connect("127.0.0.1", 5001);

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[1024];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            stream.Close();

            if (MessageBox.Show("Reply: " + responseData + "  Try again?", "Try again?", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                break;
            }

        }

来源:https://stackoverflow.com/questions/34864391/do-i-have-to-create-a-new-tcpclient-for-each-message-i-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!