簡體   English   中英

從客戶端(Unity)發送UDP數據,並從服務器將數據發送回同一客戶端

[英]Send UDP data from client (Unity) and send data back to same client from server

我在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);

    }

編輯:

我修復了它,並在每次收到消息時都重新連接到服務器/客戶端,從而解決了該問題。

你應該叫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相同)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM