套接字没有收到消息

时间:2016-10-01 11:42:13

标签: c# sockets networking

当我使用" 127.0.0.1"在同一台计算机上,它工作得很好。如果我尝试使用服务器的公共IP地址,它不起作用(实际上我得到套接字错误)。如果我把它作为ipaddress.any它不会给出错误,但它也不起作用。我想也许是因为我在同一台电脑上,所以我将服务器放在笔记本电脑上的台式机和客户端上,然后将笔记本电脑连接到手机的热点,以便ipaddress是不同。它仍然无法运作。邮件已发送,但从未收到过。我做错了什么?

struct DataPacket
{
    public IPEndPoint destination;
    public byte[] data;

    public DataPacket(IPEndPoint destination, byte[] data)
    {
        this.destination = destination;
        this.data = data;
    }
}

AsyncPriorityQueue<DataPacket> queuedReceiveData = new AsyncPriorityQueue<DataPacket>(NetworkConstants.MAX_PLAYERS_PER_SERVER, false);
Socket sck;
IPEndPoint ipEndPoint;
bool listening = true;
bool processing = true;

void Start()
{
    sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
#if SERVER
    ipEndPoint = new IPEndPoint(IPAddress.Any, NetworkConstants.SERVER_PORT);
    sck.Bind(ipEndPoint);
#else
    ipEndPoint = new IPEndPoint(IPAddress.Parse(NetworkConstants.SERVER_IP), NetworkConstants.SERVER_PORT);

    EndPoint ep = new IPEndPoint(IPAddress.Any, 0); // doesn't work at all
    //EndPoint ep = new IPEndPoint(IPAddress.Parse(NetworkConstants.SERVER_IP), 0); // says requested address is not valid in its context
    //EndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0); // works only on same computer

    sck.Bind(ep);
#endif
    new Thread(() => ListenForData()).Start();
    new Thread(() => ProcessData()).Start();

#if !SERVER
    SerializeCompact.BitStream bs = new SerializeCompact.BitStream();
    bs.Write(Headers.Connect, minHeader, maxHeader);
    SendData(bs.GetByteArray());
#endif
}

void OnDestroy()
{
    listening = false;
    processing = false;
    sck.Close();
}

public void SendData(byte[] data)
{
    var packet = queuedSendData.Dequeue();
    sck.SendTo(data, 0, data.Length, SocketFlags.None, ipEndPoint);
    print("message sent to server");
}

public void SendDataTo(byte[] data, IPEndPoint endPoint)
{
    var packet = queuedSendData.Dequeue();
    sck.SendTo(data, 0, data.Length, SocketFlags.None, endPoint);
    print("message sent to client");
}

void ListenForData()
{
    while (listening)
    {
        EndPoint endPoint = ipEndPoint;

        byte[] buffer = new byte[1024];
        int rec = sck.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint);
        Array.Resize(ref buffer, rec);

        queuedReceiveData.Enqueue(new DataPacket((IPEndPoint) endPoint, buffer), 0);
        print("received message");

        ProcessData(buffer);
    }
}

void ProcessData()
{
    while (processing)
    {
        var rcv = queuedReceiveData.Dequeue(); // blocks until an item can be dequeued
        byte[] data = rcv.data;
        IPEndPoint ep = rcv.destination;

        // process data...

    }
}

0 个答案:

没有答案