2014-12-06 68 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

相關問題