2014-12-06 22 views
1

Pre:如何获取套接字中收到的数据的长度?

我有客户端和服务器。我将一些数据从客户端(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

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

如果你改变你的while循环是这样,那么你将有你正在寻找的价值:

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

没错。说你。我尝试在'socketForClient'属性中找到消息大小:( – 2014-12-06 10:55:21

+0

)我只是意识到,我通过客户端发送'exit'消息并收到'exit \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0'为什么? – 2014-12-06 11:23:37

+0

如果您将代码作为新问题的一部分发布,我会为您寻找,而不是试图将其粘贴到这里的评论:) – 2014-12-06 11:25:01

相关问题