2015-09-06 100 views
0

我想在c#中使客户端服务器appilcation。在客户端,我向服务器发送hello消息,服务器收到消息。 一旦服务器收到消息,它应该向客户端发回消息,指示已收到消息。基本上是一种承认。 我的问题是客户端没有收到服务器的消息。 停机是我的客户端和服务器的代码。c#客户端服务器使用UDP连接

客户端部分:

string x = "192.168.1.4"; 
IPAddress add = IPAddress.Parse(x); 
IPEndPoint point = new IPEndPoint(add, 2789); 

using (UdpClient client = new UdpClient()) 
{ 
    byte[] data = Encoding.UTF8.GetBytes("Hello from client"); 
    client.Send(data, data.Length, point); 

    string serverResponse = Encoding.UTF8.GetString(client.Receive(ref point)); 

    Console.WriteLine("Messahe received from server:"+ serverResponse); 
} 

服务器部分:

try 
{ 
    while (true) 
    { 
     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789); 
     Console.WriteLine("Client address is:" + groupEP.Address.ToString()); 
     Console.WriteLine("Client port is:" + groupEP.Port.ToString()); 

     byte[]data = new byte[1024]; 
     UdpClient listener = new UdpClient(2789); 

     Console.WriteLine("Waiting for client"); 
     byte[] bytes = listener.Receive(ref groupEP); 
     Console.WriteLine("Received Data:"+ Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 

     //sending acknoledgment 
     string welcome = "Hello how are you from server?"; 
     byte[]d1 = Encoding.ASCII.GetBytes(welcome); 
     listener.Send(d1, d1.Length, groupEP); 
     Console.WriteLine("Message sent to client back as acknowledgment"); 
    } 
} 

回答

0

我编译你的代码,它工作,所以你的问题是一个 “外” 的问题,如:

  • 防火墙阻塞了某些东西(连接或服务器绑定)。

  • 您在与服务器不同的计算机上测试客户端,并使用错误的ip。
    如果你在同一台机器上测试,你可以使用特殊的ip 127.0.0.1(又名DNS本地主机)。 127.0.0.1总是指正在运行代码的计算机。如果您的本地IP确实发生变化,使用这个特殊的IP可能会避免您在将来遇到麻烦

顺便说一下,在你的服务器代码,您应该重用的“听众”领域,而每个互为作用()如

 IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789); 
     Console.WriteLine("Client address is:" + groupEP.Address.ToString()); 
     Console.WriteLine("Client port is:" + groupEP.Port.ToString()); 

     byte[] data = new byte[1024]; 
     UdpClient listener = new UdpClient(2789); 

     while (true) 
     { 
      Console.WriteLine("Waiting for client"); 
      byte[] bytes = listener.Receive(ref groupEP); 
      Console.WriteLine("Received Data:" + Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 

      //sending acknoledgment 
      string welcome = "Hello how are you from server?"; 
      byte[] d1 = Encoding.ASCII.GetBytes(welcome); 
      listener.Send(d1, d1.Length, groupEP); 
      Console.WriteLine("Message sent to client back as acknowledgment"); 

     } 
+0

THX的答复。我尝试了你提到的步骤,但仍然是同样的问题。 –