How can I get use a TcpClient object to send multiple messages?

This is driving me up the nearest wall. I've spent all day trying to do one simple thing, and this isn't even for a customer. It's for a test application to make sure my customer code works.

I have a WinForms project written in C# using VS 2012. It sends TCP messages to my program, which has to receive them, parse them, and update a database. The test application happily sends one message and receives the ack message that comes back, but I can't get it to send a second message.

At first I was using a Socket object, but I can't get a TcpClient object to work either. Here's the code:

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

I put a breakpoint on the call to client.Connect(). The first call to that method succeeds, and the message is sent. But when the breakpoint is hit the second time, the client object's Connected property is false. But even though it's false, the call to Connect() fails with an exception that says the object is already connected.

What is the accepted way for a TCP client to send a message, wait for a while, and then send a second message?

by CedricCicada via /r/csharp

Leave a Reply