Do I have to create a new TcpClient for each messa

2019-09-12 03:57发布

问题:

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;
            }

        }