How to get length of data received in socket?

4.6k Views Asked by At

Pre:

I have client and server. I send some data from client (win forms) to the server (console). I send data using this on the client:

try {
    sock = client.Client;

    data = "Welcome message from client with proccess id " + currentProcessAsText;
    sock.Send(Encoding.ASCII.GetBytes(data));
}
catch
{
    // say there that 
}

On server I receive data by this:

private void ServStart()
{
    Socket ClientSock; // сокет для обмена данными.
    string data;
    byte[] cldata = new byte[1024]; // буфер данных
    Listener = new TcpListener(LocalPort);
    Listener.Start(); // начали слушать
    Console.WriteLine("Waiting connections [" + Convert.ToString(LocalPort) + "]...");

    for (int i = 0; i < 1000; i++)
    {
        Thread newThread = new Thread(new ThreadStart(Listeners));
        newThread.Start();
    }
}

private void Listeners()
{
    Socket socketForClient = Listener.AcceptSocket();
    string data;
    byte[] cldata = new byte[1024]; // буфер данных
    int i = 0;

    if (socketForClient.Connected)
    {
        string remoteHost = socketForClient.RemoteEndPoint.ToString();
        Console.WriteLine("Client:" + remoteHost + " now connected to server.");
        while (true)
        {
            i = socketForClient.Receive(cldata);
            if (i > 0)
            {
                data = "";
                data = Encoding.ASCII.GetString(cldata).Trim();
                if (data.Contains("exit"))
                {
                    socketForClient.Close();
                    Console.WriteLine("Client:" + remoteHost + " is disconnected from the server.");
                    break;
                }
                else
                {
                    Console.WriteLine("\n----------------------\n" + data + "\n----------------------\n");
                }
            }
        }
    }   
} 

Server start threads and starting listening socket on each.

Problem:

When client connects or sends message, server outputs message received + ~ 900 spaces (because buffer is 1024). How I can get received data length and allocate so much memory as needed for this data?

1

There are 1 best solutions below

5
On BEST ANSWER

Per the MSDN article, the integer returned by Receive is the number of bytes received (this is the value you have assigned to i).

If you change your while loop to be like this then you will have the value you are looking for:

int bytesReceived = 0;
while (true)
    {
        i = socketForClient.Receive(cldata);
        bytesReceived += i;
        if (i > 0)
        {
            // same code as before
        }
    }