2011-11-25 181 views
5

我发现这个伟大的代码在MSDN上的UDP客户端/服务器连接,但客户端只能发送到服务器,它不能回复。我如何做到这一点,以便服务器可以响应发送消息的客户端。 服务器UDP侦听器响应客户端

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Security.Cryptography; 


namespace UDP_Server 
{ 
    class Program 
    { 
     private const int listenPort = 11000; 

     private static void StartListener() 
     { 
      bool done = false; 

      UdpClient listener = new UdpClient(listenPort); 
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); 
      try 
      { 
       while (!done) 
       { 
        Console.WriteLine("Waiting for broadcast"); 
        byte[] bytes = listener.Receive(ref groupEP); 
        Console.WriteLine("Received broadcast from {0} :\n {1}\n",groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length)); 
       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.ToString()); 
      } 
      finally 
      { 
       listener.Close(); 
      } 
     } 

     public static int Main() 
     { 
      StartListener(); 

      return 0; 
     } 
    } 

} 

而且客户

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Security.Cryptography; 

namespace UDP_Client 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Send("TEST STRING"); 
      Console.Read(); 
     } 
     static void Send(string Message) 
     { 
      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
      IPAddress broadcast = IPAddress.Parse("10.1.10.117"); 
      byte[] sendbuf = Encoding.ASCII.GetBytes(Message); 
      IPEndPoint ep = new IPEndPoint(broadcast, 11000); 
      s.SendTo(sendbuf, ep); 
     } 
    } 
} 

回答

8

只要做到这一点反过来。在客户端上拨打StartListener,它可以像服务器一样接收udp数据。

在您的服务器上只需要发送数据与客户端的代码。

0

这是相同的代码,只是具有相反的角色。客户端需要侦听某个端口,并且服务器将消息发送到客户端的端点,而不是广播地址。

相关问题