如何获取socket中收到的数据长度?

时间:2014-12-06 10:48:19

标签: c# sockets system.net.sockets

预:

我有客户端和服务器。我将一些数据从客户端(win表单)发送到服务器(控制台)。我在客户端上使用它发送数据:

try {
    sock = client.Client;

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

在服务器上我通过以下方式接收数据:

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

服务器启动线程并在每个线程上启动侦听套接字。

问题:

当客户端连接或发送消息时,服务器输出消息接收+ ~900个空格(因为缓冲区为1024)。我如何获得接收的数据长度并根据需要为这些数据分配如此多的内存?

1 个答案:

答案 0 :(得分:1)

根据MSDN article,Receive返回的整数是收到的字节数(这是您分配给i的值)。

如果您将while循环更改为此类,那么您将拥有所需的值:

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