发送UDP广播,需要接收来自所有客户端的消息

时间:2016-06-15 10:21:15

标签: c# sockets udp

我正在开发一个客户端需要连接的服务器应用程序。 但我不希望我的用户输入IP地址...我希望客户端发现在端口4800上运行的所有服务器(在我的情况下)

这是我的服务器代码:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    static ThreadStart ts = new ThreadStart(start_server);
    Thread thread = new Thread(ts);
    private void Form1_Load(object sender, EventArgs e)
    {


        thread.Start();
    }

    private static void start_server()
    {
        //Start server
        Socket server = new Socket(AddressFamily.InterNetwork,
        SocketType.Dgram, ProtocolType.Udp);
        Console.Write("Running server..." + Environment.NewLine);
        server.Bind(new IPEndPoint(IPAddress.Any, 4800));

        while (true)
        {
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint tempRemoteEP = (EndPoint)sender;
            byte[] buffer = new byte[1000];
            //Recive message from anyone.
            server.ReceiveFrom(buffer, ref tempRemoteEP);

            Console.Write("Server got '" + Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 }) +
            "' from " + tempRemoteEP.ToString() +
            Environment.NewLine);
            string access_code = Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 });
            if (access_code == "7uz876t5r798qwe12")
            {
                Console.Write("Sending Response to " + tempRemoteEP.ToString() +
                Environment.NewLine);

                //Replay to client

                server.SendTo(Encoding.ASCII.GetBytes("ACCESS GRANTED"),
                tempRemoteEP);
            }
            else
            {
                Console.WriteLine("Client Access denied!");
                server.SendTo(Encoding.ASCII.GetBytes("ACCESS DENIED"),
                tempRemoteEP);
            }

        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Environment.Exit(Environment.ExitCode);
    }
}

那就是我的客户端发送UDP广播:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
        ProtocolType.Udp);
    private void button1_Click(object sender, EventArgs e)
    {



        IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 4800);

        //Allow sending broadcast messages
        client.SetSocketOption(SocketOptionLevel.Socket,
        SocketOptionName.Broadcast, 1);

        //Send message to everyone
        client.SendTo(Encoding.ASCII.GetBytes("7uz876t5r798qwe12"), AllEndPoint);
        Console.Write("Client send '1' to " + AllEndPoint.ToString() +
        Environment.NewLine);

        IPEndPoint _sender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint tempRemoteEP = (EndPoint)_sender;
        byte[] buffer = new byte[1000];

        string serverIp;
        try
        {

            client.SetSocketOption(SocketOptionLevel.Socket,
            SocketOptionName.ReceiveTimeout, 3000);
            client.ReceiveFrom(buffer, ref tempRemoteEP);
            Console.Write("Client got '" + buffer[0] + "' from " +
            tempRemoteEP.ToString() + Environment.NewLine);
            MessageBox.Show(Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 }));
            //Get server IP (ugly)
            serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
            listServer.Items.Add(serverIp);

        }
        catch (Exception ex)
        {
            //Timout. No server answered.
            MessageBox.Show(ex.Message);
        }

        // MessageBox.Show(serverIp);
    }

}

正在运行的所有服务器都在接收广播,但我的客户端只接收1个IP地址。也许是第一个到达客户的回复?

我如何能够发现在我的港口上收听的所有服务器?

1 个答案:

答案 0 :(得分:0)

您的客户只拨打ReceiveFrom()一次,因此只会收到一个回复​​。您需要在循环中调用ReceiveFrom(),并运行循环几秒钟,以便为多个服务器提供足够的响应时间。