改一下端口号就能互发消息
using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;namespace C1{ class Program { static void Main(string[] args) { IPAddress ip = null; IPAddress[] ips = Dns.GetHostAddresses(""); foreach (var v in ips) { if (v.AddressFamily == AddressFamily.InterNetwork) { ip = v; break; } } IPEndPoint iep = new IPEndPoint(ip, 8001); string Addrstr = "224.0.0.6"; IPAddress muticastAddress = IPAddress.Parse(Addrstr); Console.WriteLine("在端口{0}监听,加入的多播组为{1}", iep.Port, muticastAddress); UdpClient client = new UdpClient(iep); client.JoinMulticastGroup(muticastAddress); IPEndPoint remoteEp = null; var t1 = Task.Run(() => { while (true) { var result = client.Receive(ref remoteEp); Console.WriteLine("来自{0}:{1}", remoteEp, Encoding.Unicode.GetString(result)); } } ); var t2 = Task.Run(() => { string str = Console.ReadLine(); byte[] bytes = Encoding.Unicode.GetBytes(str); client.Send(bytes, bytes.Length, Addrstr, 8001); client.Send(bytes, bytes.Length, Addrstr, 8002); client.Send(bytes, bytes.Length, Addrstr, 8003); }); t1.Wait(); t2.Wait(); } }}
评论