我在MSDN上找到了这个用于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); } } }
Jan.. 8
只是反过来做.调用StartListener
上的客户端,它可以收到这样一个服务器的UDP数据.
在您的服务器上只需使用客户端代码发送数据.
只是反过来做.调用StartListener
上的客户端,它可以收到这样一个服务器的UDP数据.
在您的服务器上只需使用客户端代码发送数据.