在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
服务端程序: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; using System.Threading; namespace UDP_Server { class Program { static Socket server; static void Main(string[] args) { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001));//绑定端口号和IP Console.WriteLine("服务端已经开启"); Thread t = new Thread(ReciveMsg);//开启接收消息线程 t.Start(); Thread t2 = new Thread(sendMsg);//开启发送消息线程 t2.Start(); } /// <summary> /// 向特定ip的主机的端口发送数据报 /// </summary> static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000); while (true) { string msg = Console.ReadLine(); server.SendTo(Encoding.UTF8.GetBytes(msg), point); } } /// <summary> /// 接收发送给本机ip对应端口号的数据报 /// </summary> static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = server.ReceiveFrom(buffer, ref point);//接收数据报 string message = Encoding.UTF8.GetString(buffer,0,length); Console.WriteLine(point.ToString()+ message); } } } } 客户端程序 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Threading; namespace UDP_client { class Program { static Socket client; static void Main(string[] args) { client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000)); Thread t = new Thread(sendMsg); t.Start(); Thread t2 = new Thread(ReciveMsg); t2.Start(); Console.WriteLine("客户端已经开启"); } /// <summary> /// 向特定ip的主机的端口发送数据报 /// </summary> static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001); while(true){ string msg = Console.ReadLine(); client.SendTo(Encoding.UTF8.GetBytes(msg), point); } } /// <summary> /// 接收发送给本机ip对应端口号的数据报 /// </summary> static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = client.ReceiveFrom(buffer, ref point);//接收数据报 string message = Encoding.UTF8.GetString(buffer, 0, length); Console.WriteLine(point.ToString() + message); } } } }
http://download.csdn.net/detail/u011484013/9488304 来源:http://blog.csdn.net/u011484013/article/details/51131267 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论