2015-09-06 99 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的答覆。我嘗試了你提到的步驟,但仍然是同樣的問題。 –