c#udp广播包未收到

时间:2017-01-12 17:19:30

标签: c# sockets networking udp broadcast

我进入UDP并决定只是为了练习而进行一次小聊天。 我遇到了一个问题,我自己无法弄明白。

我创建了两个完全相同的c#控制台程序(Just Port不同)

我发送UDP广播包,然后想要在第二个控制台程序上接收它。我发送广播的程序接收到它而其他程序没有接收到会发生什么。反过来也是如此。

我已经关闭了防火墙 - >不改变任何东西。

我发给你整个代码,我希望你们能帮助我,我真的很想继续前进!非常感谢你!

class Program
{
    const int PORT = 10101;
    private static readonly UdpClient udpclient = new UdpClient(PORT);
    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        udpclient.EnableBroadcast = true;
        //bool for calling async receiver just once
        bool receiving = false;
        Console.WriteLine("Chat 2");
        //to keep while loop running --> change later
        bool keepchatting = true;
        #region keepchating loop
        while (keepchatting)
        {
            if (!receiving)
            {
                startlistening();
            }
            receiving = true;
            newmessage();
        }
    }
    #endregion

    //new message --> call sendmessage to broadcast text via UDP
    public static void newmessage()
    {
        string msg;
        msg = Console.ReadLine();
        byte[] message = Encoding.ASCII.GetBytes(msg);
        sendmessage(message);
    }

    //Broadcast text via UDP
    public static void sendmessage(byte[] tosend)
    {
        UdpClient client = new UdpClient();
        client.EnableBroadcast = true;
        IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT);
        client.Send(tosend, tosend.Length, ip);
        client.Close();
        Console.WriteLine("Sent!");
    }

    static IAsyncResult ar = null;
    //Setup Async Receive Method 
    public static void startlistening()
    {
        ar = udpclient.BeginReceive(RecievedMessage, new object());
    }

    //Message
    public static void RecievedMessage(IAsyncResult ar)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
        byte[] bytes = udpclient.EndReceive(ar, ref ip);
        string msg = Encoding.ASCII.GetString(bytes);
        Console.WriteLine("Received: " + msg);
        startlistening();
    }

}

2 个答案:

答案 0 :(得分:1)

我只更改了代码的两个部分,在每个客户端上设置另一个客户端的远程端口号,试试这个:

在一位客户上:

const int PORT = 10101;
const int PORT_Remote = 10102;

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);

在另一个客户端:

const int PORT = 10102;
const int PORT_Remote = 10101;

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);

答案 1 :(得分:0)

我最近写了一个应用程序,我在笔记本电脑上的两个应用程序之间来回发送套接字消息。我使用127.0.0.1(本地主机的默认IP地址)作为IP地址。你能试试吗?