UDP客户端可以接收从同一台计算机发送的数据,但不能通过WLAN

时间:2019-03-25 00:53:11

标签: c# sockets networking udp client

我已经设置了UDP客户端以使用C#接收数据。客户端设置为使用从我的WiFi路由器分配的IP地址进行接收。如果我在与发件人相同的计算机上运行程序,则客户端可以接收数据。但是,当我在另一台计算机上尝试接收客户端时,该客户端没有收到任何数据。

我尝试将UDP客户端中的IP地址设置为IPAddress。我尝试了其他端口,但这也行不通。

将接收方的IP地址设置为发送方的IP地址。发送者IP地址设置为接收者地址。端口号相同。

代码的重要部分始于Private Void Receive()。

using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPReceive : MonoBehaviour
{

    // receiving Thread
    Thread receiveThread;

    // udpclient object
    UdpClient client;

    //public string IP = "192.168.0.1";
    public int port; // define > init

    IPAddress ipaddress = IPAddress.Parse("192.168.0.100");

    // infos
    public string lastReceivedUDPPacket = "";
    public string allReceivedUDPPackets = ""; // clean up this from time to time!


    // start from shell
    private static void Main()
    {
        UDPReceive receiveObj = new UDPReceive();
        receiveObj.init();

        string text = "";
        do
        {
            text = Console.ReadLine();
        }
        while (!text.Equals("exit"));
    }
    // start from unity3d
    public void Start()
    {

        init();
    }


    // init
    private void init()
    {
        print("UDPSend.init()");

        // define port
        port = 27015;

        // status
        print("Sending to 192.168.0.100 : " + port);
        print("Test-Sending to this Port: nc -u 192.168.0.100  " + port + "");

        receiveThread = new Thread(
            new ThreadStart(ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start();

    }

    // receive thread
    private void ReceiveData()
    {

        client = new UdpClient(port);
        while (true)
        {

            try
            {

                IPEndPoint anyIP = new IPEndPoint(ipaddress, port);
                byte[] data = client.Receive(ref anyIP);

                string text = Encoding.UTF8.GetString(data);

                print(">> " + text);

                // latest UDPpacket
                lastReceivedUDPPacket = text;

                // ....
                allReceivedUDPPackets = allReceivedUDPPackets + text;

            }
            catch (Exception err)
            {
                print(err.ToString());
            }
        }
    }

    private void OnDisable()
    {
        if (receiveThread != null)
        {
            receiveThread.Abort();
            client.Close();
        }
    }

    // getLatestUDPPacket
    // cleans up the rest
    public string getLatestUDPPacket()
    {
        allReceivedUDPPackets = "";
        return lastReceivedUDPPacket;
    }
}

我将客户端IP地址设置为192.168.0.100,这是发送方的IP地址。

当我在计算机上运行程序时,客户端会收到。它不能在其他计算机上接收。

我还尝试将客户端IP地址设置为其本地IP地址,但这也不起作用。

客户端似乎只能通过本地主机接收。

有什么我想念的吗?我什至尝试打开防火墙以允许端口27015上的数据。同样没有用。

0 个答案:

没有答案