2016-05-31 38 views
2

發送第二條消息,我想通過TCP/IP使用TCPClientTCPListner無法通過TCP/IP

下面的C#應用​​程序發送的消息是我的代碼,我從CodeProject網站獲得。

客戶code written over btn click

try 
     { 
      TcpClient tcpclnt = new TcpClient(); 
      Console.WriteLine("Connecting....."); 

      tcpclnt.Connect("192.168.0.102", 8001); 
      // use the ipaddress as in the server program 

      Console.WriteLine("Connected"); 
      //Console.Write("Enter the string to be transmitted : "); 

      String str = textBox1.Text; 
      Stream stm = tcpclnt.GetStream(); 

      ASCIIEncoding asen = new ASCIIEncoding(); 
      byte[] ba = asen.GetBytes(str); 
      Console.WriteLine("Transmitting....."); 

      stm.Write(ba, 0, ba.Length); 

      byte[] bb = new byte[100]; 
      int k = stm.Read(bb, 0, 100); 

      for (int i = 0; i < k; i++) 
       Console.Write(Convert.ToChar(bb[i])); 


      tcpclnt.Close(); 
     } 

     catch (Exception ex) 
     { 
      Console.WriteLine("Error..... " + ex.Message); 
     } 

服務器code written on form_load

try 
     { 
      IPAddress ipAd = IPAddress.Parse("192.168.0.102"); 
      // use local m/c IP address, and 
      // use the same in the client 

      /* Initializes the Listener */ 
      TcpListener myList = new TcpListener(ipAd, 8001); 

      /* Start Listeneting at the specified port */ 
      myList.Start(); 

      Console.WriteLine("The server is running at port 8001..."); 
      Console.WriteLine("The local End point is :" + 
           myList.LocalEndpoint); 
      Console.WriteLine("Waiting for a connection....."); 

      Socket s = myList.AcceptSocket(); 
      Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); 

      byte[] b = new byte[100]; 
      int k = s.Receive(b); 
      Console.WriteLine("Recieved..."); 
      string str = string.Empty; 
      for (int i = 0; i < k; i++) 
      { 
       Console.Write(Convert.ToChar(b[i])); 
       str = str + Convert.ToChar(b[i]); 

      } 
      label1.Text = str; 
      ASCIIEncoding asen = new ASCIIEncoding(); 
      s.Send(asen.GetBytes("The string was recieved by the server.")); 
      Console.WriteLine("\nSent Acknowledgement"); 
      /* clean up */ 
      s.Close(); 
      // myList.Stop(); 

     } 

這裏就client,我要寄給在tcp寫在文本字符串,並將其深受server收到。

但是,當我試圖發送另一個字符串,它失敗沒有任何exception和客戶端應用程序掛起無限時間。

這裏有什麼問題?

+2

雖然這不是您的主要問題:TCP/IP是基於流的,而不是基於消息的。像這樣的代碼是致命的缺陷:你可能永遠不會假設對'Receive'的特定調用接收到特定數量的字節。您可以確定的是,如果客戶端寫入「N」個字節,則「接收」調用的某些組合最終將收到所有「N」個字節。像這樣的代碼可以在本地套接字上的測試設置中正常工作,並且在實際網絡中工作時會失敗。 –

回答

1

服務器應始終處於監聽模式,即服務器代碼應處於while循環,以便它可以連續接受客戶端。您的服務器將接受一個客戶端,然後關閉。因此,如果您單擊客戶端的按鈕,新客戶端會嘗試連接到服務器,但現在服務器將不可用。

1

查看您提供的代碼,服務器只會嘗試從客戶端讀取1條消息,因此需要放入循環以從客戶端讀取多條傳入消息,處理消息併發送響應,然後獲取更多的消息。

另請注意,服務器當前期望只有一個客戶端連接,處理該客戶端,然後關閉。

客戶端在示例中基本上設置相同,因此您無法修改其中一個如何工作而不修改其他客戶端。