2016-05-31 56 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条消息,因此需要放入循环以从客户端读取多条传入消息,处理消息并发送响应,然后获取更多的消息。

另请注意,服务器当前期望只有一个客户端连接,处理该客户端,然后关闭。

客户端在示例中基本上设置相同,因此您无法修改其中一个如何工作而不修改其他客户端。