2012-06-11 62 views
1

我在計算爲什麼我只能從運行在我的計算機上的服務器應用程序(LocalHost)收到一個答覆時遇到了一些問題。我沒有這個服務器應用程序的源代碼,但它是一個Java應用程序。發送的消息是xml結構,必須以EoT標籤結束。C#套接字。僅能夠收到第一條消息

的通信:

  1. Client連接斷絕。
  2. 客戶端發送消息到服務器。
  3. 服務器發送消息到客戶端。
  4. 客戶端發送消息到服務器。
  5. 服務器發送一個傳輸結束字符。
  6. 客戶端發送消息到服務器。
  7. 服務器發送一個傳輸結束字符。

這是怎麼我的客戶端連接,發送和接收:

public bool ConnectSocket(string server, int port) 
{ 
System.Net.IPHostEntry hostEntry = null; 

    try 
    { 
     // Get host related information. 
     hostEntry = System.Net.Dns.GetHostEntry(server); 
    } 
    catch (System.Exception ex) 
    { 
      return false; 
    } 


    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid 
    // an exception that occurs when the host IP Address is not compatible with the address family 
    // (typical in the IPv6 case). 
    foreach (System.Net.IPAddress address in hostEntry.AddressList) 
    { 
      System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(address, port); 
      System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, System.Net.Sockets.SocketType.Stream, 
                       System.Net.Sockets.ProtocolType.Tcp); 
      tempSocket.Connect(ipe); 

      if (tempSocket.Connected) 
      { 
       m_pSocket = tempSocket; 
       m_pSocket.NoDelay = true; 
       return true; 
      } 
      else 
       continue; 
     } 
     return false; 
    } 
} 

public void Send(string message) 
{ 
    message += (char)4;//We add end of transmission character 
    m_pSocket.Send(m_Encoding.GetBytes(message.ToCharArray())); 
} 

private void Recive() 
{ 
    byte[] tByte = new byte[1024]; 
    m_pSocket.Receive(tByte); 
    string recivemessage = (m_Encoding.GetString(tByte)); 
} 

回答

3

Receive代碼看起來非常錯誤的;你不應該假設數據包到達與服務器發送消息相同的結構--TCP只是一個流。所以:你必須趕上從Receive返回,看看你收到多少字節。它可以是一條消息,整條消息,多條完整消息,或一條消息的後半部分和下一條消息的前半部分的一部分。通常情況下,您需要某種「成幀」決策,這可能意味着「按LF字符分割的消息」,或者可能意味着「每個消息的長度以網絡字節順序整數爲前綴,4個字節」。這通常意味着你需要緩衝直到你有一個完整的幀,擔心在下一幀的緩衝區末尾的備用數據。鍵位增加,但:

int bytes = m_pSocket.Receive(tByte); 
// now process "bytes" bytes **only** from tByte, nothing that this 
// could be part of a message, an entire message, several messages, or 
// the end of message "A", the entire of message "B", and the first byte of 
// message "C" (which might not be an entire character) 

特別是,文本格式,你不能開始解碼,直到你確定你有緩衝整個消息,因爲一個多字節字符可能兩條消息之間拆分。

您的接收循環中也可能存在問題,但您不會顯示該問題(沒有電話Receive),因此我們無法發表評論。

相關問題