Ahmed Mujtaba
Ahmed Mujtaba

Reputation: 2248

continuously write data using tcpClient

I'm trying to send data via tcpClient connection to operate a device which receives input and does the required operation. On the server, data is received in a loop and values are set in an array. The code looks something like this:

client = server.available();
//Receive Data
 while(client.available()){  
 for(int i = 7; i<11; ++i){
  String msg = client.readStringUntil('\n');
  senddata[i] = msg.toInt();
   msg ="";  
  }

My client side function looks like this:

static void Connect(String server, String message)
    {
        try
        {
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer 
            // connected to the same address as specified by the server, port
            // combination.
            Int32 port = 85;
            TcpClient client = new TcpClient(server, port);

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


            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer.

            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent: {0}", message);

            // Receive the TcpServer.response.

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

            // 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);

            Console.WriteLine("Received: {0}", responseData);

            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

I wanna be able to write data continuously before closing the connection. Essentially something like this:

    int[] data = new int[4];
    data[0] = 1;
    data[0] = 1;
    data[0] = 1;
    data[0] = 1;

    for (int i = 0; i < data.Length; i++)
    {
        Connect("192.168.1.125", data[i].ToString());
    }

Currently, the data is sent and connection is closed and server doesn't get more data to process. I have tried different solutions but without any luck.

Edit

I have tried running the below code in a loop which writes data to stream:

            for (int i = 0; i < 4; i++)
        {
            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent: {0}", message);

            // Receive the TcpServer.response.

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

            // 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);

            Console.WriteLine("Received: {0}", responseData);
        }
            // Close everything.
            stream.Close();
            client.Close();

I get the following error: Additional information: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.

Upvotes: 2

Views: 3443

Answers (1)

CodeFuller
CodeFuller

Reputation: 31312

Your current Connect() method opens connection, performs one write / read operation and closes the connection. You should move connection opening & close code out of the method and leave only write / read logic.

The reason why the data is not written if you don't close connection - is use of Nagle's algorithm. See this answer for the details. To fix this just set TcpClient.NoDelay to true as in code below:

static void WriteData(NetworkStream stream, String message)
{
    try
    {
        // Translate the passed message into ASCII and store it as a Byte array.
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

        // Send the message to the connected TcpServer.

        stream.Write(data, 0, data.Length);

        Console.WriteLine("Sent: {0}", message);

        // Receive the TcpServer.response.

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

        // 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);

        Console.WriteLine("Received: {0}", responseData);
    }
    catch (ArgumentNullException e)
    {
        Console.WriteLine("ArgumentNullException: {0}", e);
    }
    catch (SocketException e)
    {
        Console.WriteLine("SocketException: {0}", e);
    }
}

static void ClientCode()
{
    int[] data = new int[4];
    data[0] = 1;
    data[0] = 1;
    data[0] = 1;
    data[0] = 1;

    // Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 85;
    TcpClient client = new TcpClient(server, port);
    client.NoDelay = true;

    // Get a client stream for reading and writing.
    NetworkStream stream = client.GetStream();

    for (int i = 0; i < data.Length; i++)
    {
        WriteData(stream, data[i].ToString());
    }

    // Close everything.
    stream.Close();
    client.Close();
}

Upvotes: 1

Related Questions