使用组播有一个很大的好处,消息往只管往里面丢,接受端开个线程,不断地接收就可以了。
发送端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.0.0.1"), 3000);
EndPoint ep = (EndPoint)iep;
byte[] b = Encoding.ASCII.GetBytes("just a test!");
s.SendTo(b, ep);
s.Close();
接收端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 3000);
EndPoint ep=(EndPoint)iep;
s.Bind(iep);
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,new MulticastOption(IPAddress.Parse("224.0.0.1")));
byte[]b=new byte[1024];
s.ReceiveFrom(b,ref ep);
string test;
test = System.Text.Encoding.ASCII.GetString(b);
Console.WriteLine(test);
s.Close();
Console.ReadKey();
发送端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.0.0.1"), 3000);
EndPoint ep = (EndPoint)iep;
byte[] b = Encoding.ASCII.GetBytes("just a test!");
s.SendTo(b, ep);
s.Close();
接收端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 3000);
EndPoint ep=(EndPoint)iep;
s.Bind(iep);
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,new MulticastOption(IPAddress.Parse("224.0.0.1")));
byte[]b=new byte[1024];
s.ReceiveFrom(b,ref ep);
string test;
test = System.Text.Encoding.ASCII.GetString(b);
Console.WriteLine(test);
s.Close();
Console.ReadKey();