0

我制作了一个使用 UDP 多播套接字的服务器。我能够在我的网络上运行服务器并访问每个客户端。问题是我现在正试图联系通过 hamachi 连接的客户。我读过它支持多播,但是似乎没有收到消息。

这就是我创建 udpclient 的方式:

        localIPaddress = IPAddress.Any;
        multicastAddress = = IPAddress.Parse("233.0.0.2");
        multicastPort = 7778;

        // Create endpoints
        multicastEndPoint = new IPEndPoint(multicastAddress, multicastPort);
        remoteEndPoint = new IPEndPoint(_localIPaddress, multicastPort);

        // Create and configure UdpClient
        socket = new UdpClient();
        // The following three lines allow multiple clients on the same PC
        socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        socket.ExclusiveAddressUse = false;
        // Bind, Join
        socket.Client.Bind(remoteEndPoint);
        socket.JoinMulticastGroup(multicastAddress);

        // Start listening for incoming data
        socket.BeginReceive(new AsyncCallback(ReceiveCallback), null);

这是我接收信息的方式:

    private void ReceiveCallback(IAsyncResult _result)
    {
        try
        {
            IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, multicastPort);
            byte[] data = socket.EndReceive(_result, ref clientEndPoint);
            // Restart listening for udp data packages
            socket.BeginReceive(new AsyncCallback(ReceiveCallback), null);

            if (data.Length < 4)
            {
                Disconnect();
                return;
            }

            // Handle Data
            using (Packet packet = new Packet(data))
            {
                HandleData(packet);
            }
        }
        catch (Exception ex)
        {
            if (instance.isConnected)
                Debug.Log($"Error receiving UDP Multicast data: {ex}");
        }
    }

这就是我发送信息的方式:

    public void SendData(Packet _packet)
    {
        try
        {
            socket.Send(_packet.ToArray(), _packet.Length(), multicastEndPoint);
        }
        catch (Exception ex)
        {
            Debug.Log($"Error multicasting UDP data: {ex}");
        }
    }

任何信息将不胜感激,因为没有太多关于如何解决这个问题的信息。

4

0 回答 0