Unity3d和UdpClient

Boo*_*zzz 5 c# sockets mono unity-game-engine

我想使用套接字将UDP包读入Unity3d.UDP包由另一个C#应用程序发送,该应用程序不是Unity应用程序.因此,我将以下脚本(原始源)附加到我的一个游戏对象中.不幸的是,当我运行我的项目时,Unity会冻结.谁能告诉我为什么?

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

public class InputUDP : MonoBehaviour
{
    // read Thread
    Thread readThread;

    // udpclient object
    UdpClient client;

    // port number
    public int port = 9900;

    // UDP packet store
    public string lastReceivedPacket = "";
    public string allReceivedPackets = ""; // this one has to be cleaned up from time to time

    // start from unity3d
    void Start()
    {
        // create thread for reading UDP messages
        readThread = new Thread(new ThreadStart(ReceiveData));
        readThread.IsBackground = true;
        readThread.Start();
    }

    // Unity Update Function
    void Update()
    {
        // check button "s" to abort the read-thread
        if (Input.GetKeyDown("q"))
            stopThread();
    }

    // Unity Application Quit Function
    void OnApplicationQuit()
    {
        stopThread();
    }

    // Stop reading UDP messages
    private void stopThread()
    {
        if (readThread.IsAlive)
        {
            readThread.Abort();
        }
        client.Close();
    }

    // receive thread function
    private void ReceiveData()
    {
        client = new UdpClient(port);
        while (true)
        {
            try
            {
                // receive bytes
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = client.Receive(ref anyIP);

                // encode UTF8-coded bytes to text format
                string text = Encoding.UTF8.GetString(data);

                // show received message
                print(">> " + text);

                // store new massage as latest message
                lastReceivedPacket = text;

                // update received messages
                allReceivedPackets = allReceivedPackets + text;

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

    // return the latest message
    public string getLatestPacket()
    {
        allReceivedPackets = "";
        return lastReceivedPacket;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我想使用IPC将我们的游戏逻辑与Unity连接起来(使用unity作为渲染引擎).C#应用程序包含游戏逻辑.我需要传输的数据包括所有可能的控制状态,例如不同玩家/对象的位置/方向等.两个应用程序都在同一台机器上运行.

小智 3

默认情况下,您的接收是阻塞的 - 因此更新调用正在等待接收完成。

创建客户端后添加以下内容:

client.Client.Blocking = false;
Run Code Online (Sandbox Code Playgroud)