从客户端(Unity)发送UDP数据,并从服务器将数据发送回同一客户端

时间:2018-01-27 15:38:55

标签: c# sockets unity3d networking udpclient

我在Unity制作游戏,我正在尝试从客户端向服务器发送数据并返回客户端(尝试保存实例),但是当我收到数据并尝试将数据发送回客户端时说udp客户端没有连接。

它成功地将数据从我的Unity客户端发送到服务器,但一旦到达那里,套接字就会断开连接,我无法发回任何内容。 正如你所看到的,我试图设置一些多播选项,但它似乎无法正常工作。

客户:

 private void SetupConnection()
{
    try
    {
        _thread = new Thread(ReceiveData);
        _thread.IsBackground = true;
        udpClient = new UdpClient();
        udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpClient.ExclusiveAddressUse = false;
        udpClient.Client.Bind(new IPEndPoint(IPAddress.Parse(serverAdress), 32212));
        udpClient.BeginReceive(new AsyncCallback(ReceiveUdpCallback), udpClient);

        _client = new TcpClient(serverAdress, port);
        _stream = _client.GetStream();
        _thread.Start();
        isConnected = true;
    }
    catch(Exception e)
    {
        CloseConnection();
        connectionError = true;
        Debug.Log(e.ToString());
    }

}


public void ReceiveUdpCallback(IAsyncResult ar)
{
    UdpClient c = (UdpClient)ar.AsyncState;
    IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    Byte[] receivedBytes1 = c.EndReceive(ar, ref receivedIpEndPoint);
    Debug.Log("coming in receiveudpcallback!: " + receivedBytes1);
    Dictionary<string, string> values = new Dictionary<string, string>();

    Byte[] receivedBytes;
    try
    {
        receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.StackTrace);
        return;
    }

    if (receivedBytes != null)
    {
        //byte[] dataBuffer = new byte[receivedBytesInt];
        // Array.Copy(_buffer, dataBuffer, receivedBytesInt);
        string textReceived = Encoding.ASCII.GetString(receivedBytes);
        Dictionary<string, string> data = GetDicValues(textReceived);

        HandleInputMessage(c, data);
    }
    udpClient.BeginReceive(ReceiveUdpCallback, ar.AsyncState);

}

服务器:

 private void SetupServer()
    {
        Console.WriteLine("Setting up Server...");
        _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 32211));
        _serverSocket.Listen(1);
        Console.WriteLine("Server is running...");
        _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

        IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 32212);


        udpServer = new UdpClient();
        udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpServer.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.
        udpServer.Client.Bind(new IPEndPoint(IPAddress.Any, 32212));
        udpServer.BeginReceive(new AsyncCallback(ReceiveUdpCallback), udpServer);

public void ReceiveUdpCallback(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        //Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        Console.WriteLine("coming in receiveudpcallback!");
        Dictionary<string, string> values = new Dictionary<string, string>();

        Byte[] receivedBytes;
        try
        {
            receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        }
        catch (Exception e)
        {

            Console.WriteLine(e.StackTrace);
            return;
        }

        if (receivedBytes != null)
        {
            string textReceived = Encoding.ASCII.GetString(receivedBytes);
            HandleInputMessage(c, textReceived);
        }
        else
        {

        }
        c.BeginReceive(ReceiveUdpCallback, ar.AsyncState);

    }

因此,服务器中的UdpClient实例会保存到播放器中,稍后在我的代码中,我尝试使用以下方法发送回客户端:

public void FlushUdp()
    {
        string msgToSend = "<opcode:" + opcode + ">";
        msgToSend += "<username:" + player.username + ">";

        foreach (KeyValuePair<string, string> entry in values)
        {
            msgToSend += "<" + entry.Key + ":" + entry.Value + ">";
        }

        byte[] bytesToSend = Encoding.ASCII.GetBytes(msgToSend);


        udpClient.Send(bytesToSend, bytesToSend.Length);

    }

编辑:

我修复了它,每次收到消息时都通过重新连接到服务器/客户端来解决它。

1 个答案:

答案 0 :(得分:0)

您应该只拨打c.EndReceive(...)

public void ReceiveUdpCallback(IAsyncResult ar)
{
    UdpClient c = (UdpClient)ar.AsyncState;
    IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    Byte[] receivedBytes1 = c.EndReceive(ar, ref receivedIpEndPoint);   // <----------------
    Debug.Log("coming in receiveudpcallback!: " + receivedBytes1);
    Dictionary<string, string> values = new Dictionary<string, string>();

    Byte[] receivedBytes;
    try
    {
        receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);       // <----------------
    }
    catch (Exception e)
    {
        Console.WriteLine(e.StackTrace);
        return;
    }

    if (receivedBytes != null)
    {
        //byte[] dataBuffer = new byte[receivedBytesInt];
        // Array.Copy(_buffer, dataBuffer, receivedBytesInt);
        string textReceived = Encoding.ASCII.GetString(receivedBytes);
        Dictionary<string, string> data = GetDicValues(textReceived);

        HandleInputMessage(c, data);
    }
    udpClient.BeginReceive(ReceiveUdpCallback, ar.AsyncState);

}

此外EndReceive()可能永远不会返回null,而是一个空数组。 receivedBytes.Length == 0。 0字节返回表示断开连接(与TCP相同)