65.9K
CodeProject 正在变化。 阅读更多。
Home

使用面向套接字的方法进行广播

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.05/5 (11投票s)

2007年11月21日

CPOL

2分钟阅读

viewsIcon

62842

downloadIcon

2587

此解决方案解释了一种面向套接字的方法, 用于将消息(广播消息)发送到同一 VLAN 中的客户端

引言

本解决方案解释了使用 Socket 方式向同一 VLAN(虚拟局域网)中的客户端发送消息(广播消息)。如果需要在整个 LAN(超过所有 VLAN)中进行广播,则需要使用 Remoting 而不是 Sockets。

如何使用广播向连接的局域网客户端发送消息

该应用程序由两个程序组成:“Clfrm”和“SERVfrm”。Clfrm 存在于所有局域网计算机上,SERVfrm 存在于服务器上。

当时间为凌晨 12:00 时,SERVfrm 将向所有连接的客户端(Clfrm)发送广播消息。Clfrm 将接收消息并运行警报表单以通知用户。

Using the Code

我使用以下命名空间来完成我的工作

  • System.Net
  • System.Net.Sockets

时间是一个重要因素,而且在从服务器向所有客户端发送/接收消息时没有延迟也很重要。因此,我使用了 Socket 而不是 Remoting(Remoting 可能会导致轻微延迟)。

Screenshot - Muneer.jpg

服务器代码

// Timer to Check Server Time

private void timer1_Tick(object sender, System.EventArgs e)
{
    // Display Server Time

    label1.Text = System.DateTime.Now.ToLongTimeString(); 

这里的定时器用于获取服务器时间。

if(System.DateTime.Now.Hour == 11 && System.DateTime.Now.Minute==59 && 
    System.DateTime.Now.Second==59)

检查时间是否为 11:59:59。

{
    /* Define a socket
    Dgram Socket :  Provides datagrams, which are connectionless messages
    of a fixed maximum length. 
    This type of socket is generally used for short messages, such as a name
    server or time server, since the order and reliability of message 
    delivery is not guaranteed

    AddressFamily.InterNetwork indicates that an IP version 4 addresses
    is expected when a socket connects to an end point. */ 
    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 
        ProtocolType.Udp); // Protocol Type is UDP 

    //Get the IP Broadcast address , Use The Port 9050 

    IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050); 
    //IP Broadcast Range using Port 9050 

    IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"),9050);
    byte[]   data = Encoding.ASCII.GetBytes("12");    // The Data To Sent /*

    Set Socket Options  --->  SocketOptionLevel
        Member name    Description

        IP        Socket options apply only to IP sockets. 
        IPv6        Socket options apply only to IPv6 sockets. 
        Socket        Socket options apply to all sockets. 
        Tcp        Socket options apply only to TCP sockets. 
        Udp        Socket options apply only to UDP sockets. 
        */
        //SocketOptionName.Broadcast : to enable broadcast

        sock.SetSocketOption(SocketOptionLevel.Socket, 
            SocketOptionName.Broadcast, 1);  
    sock.SendTo(data, iep1);
    sock.SendTo(data, iep2);
    sock.Close();
}
//

注意

在客户端应用程序的首次运行时,防火墙将显示以下消息。当 Clfrm 在客户端机器上运行时,它不会出现在桌面或任务管理器应用程序选项卡中。

我在 'Clfrm' 中设置了 ShowInaskbar = false,这将隐藏 'Clfrm' 在任务管理器应用程序选项卡中(它将出现在进程选项卡中),并设置了 Opacity = 2

Screenshot - Unlo.jpg

按下“解锁”以允许客户端使用 9050 端口接收来自服务器的消息。

客户端代码

//

public  string  TI ="0";
string  stringData ;

此定时器将检查 stringData 的值

private void timer1_Tick(object sender, System.EventArgs e)
{
    Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, 
       ProtocolType.Udp);

    /*
    The Socket.Bind method uses the Any field to indicate that a Socket
    instance must listen for client activity on all network interfaces.
    The Any field is equivalent to 0.0.0.0 in dotted-quad notation.
    */
    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
    //Associates a Socket with a local endpoint EndPoint ep = (EndPoint)iep;

    sock.Bind(iep);              

    byte[]  data = new byte[1024];
    int  recv = sock.ReceiveFrom(data, ref ep);// Receive Data 


    stringData = Encoding.ASCII.GetString(data, 0, recv);        

    TI=stringData;        
    sock.Close();
}

private void timer2_Tick(object sender, System.EventArgs e)
{
    if(TI == "12")
    {
        timer2.Interval = 3000;
        TI = "0";    
        stringData = "0";                
        Process.Start(Application.StartupPath+"\\ALER.exe"); // Run ALER.exe 

    }
    else
    {
        timer2.Interval =400;
    }
}
//

sock.Close(); 将关闭端口 9050 以供将来使用。

为什么使用 Socket 而不是 Remoting

  • 如果需要双向通信并且数据是一个小片段,请使用 Socket
  • 如果您想要最佳性能
  • 当客户端等待来自服务器的通知/事件时
  • Remoting 是建立在 Socket 之上的更高层。当客户端和服务器都在您的控制之下时,您可以使用 Remoting
© . All rights reserved.