有什么方法可以向同一网络上的应用程序的所有实例发送消息?

时间:2013-11-24 13:42:21

标签: c# .net networking

在我的应用程序中,我想在同一网络中通知应用程序的任何一个实例中的某些事件的所有其他实例。我有什么机制或渠道可以做到这一点?

1 个答案:

答案 0 :(得分:1)

你可以broadcast UDP packets

class Broadcst  
{  
  public static void Main()  
  {  
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,  
                ProtocolType.Udp);  
   IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);  
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);  
   string hostname = Dns.GetHostName();  
   byte[] data = Encoding.ASCII.GetBytes(hostname);  
   sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);  
   sock.SendTo(data, iep1);  
   sock.SendTo(data, iep2);  
   sock.Close();  
  }  
}  

class RecvBroadcst  
{  
  public static void Main()  
  {  
   Socket sock = new Socket(AddressFamily.InterNetwork,  
           SocketType.Dgram, ProtocolType.Udp);  
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);  
   sock.Bind(iep);  
   EndPoint ep = (EndPoint)iep;  
   Console.WriteLine("Ready to receive…");  
   byte[] data = new byte[1024];  
   int recv = sock.ReceiveFrom(data, ref ep);  
   string stringData = Encoding.ASCII.GetString(data, 0, recv);  
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());  
   data = new byte[1024];  
   recv = sock.ReceiveFrom(data, ref ep);  
   stringData = Encoding.ASCII.GetString(data, 0, recv);  
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());  
   sock.Close();  
  }  
}  

为了使其特定于应用程序,您始终可以检查传入数据是否遵循定义的模式。