本文主要是介绍c#简单的组播例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用组播有一个很大的好处,消息往只管往里面丢,接受端开个线程,不断地接收就可以了。
发送端:
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();
这篇关于c#简单的组播例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!