You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中CancellationTokenSource异常:打包后数据传输失效问题

问题描述

在Unity游戏中集成了一款内嵌式小型服务器,服务器随Unity启动运行。出现异常行为:编辑器内启动游戏时,数据传输等功能完全正常;但打包为普通构建后,数据传输彻底停止,无任何报错信息,且脚本看起来仍在执行。

临时解决方法

额外生成带有Debug日志输出的开发构建后,普通构建即可恢复正常工作。

相关脚本
public class Server : MonoBehaviour
{
    public MioData MioData;
    public MenuManager menuManager;
    public DroneFootballController droneFootballController;
    public DroneRaceController droneRaceController;
    
    private static Socket _listener;
    private CancellationTokenSource _source;
    public ManualResetEvent AllDone;
    public string _data;

    public const int Port = 8888;
    public const int Waittime = 1;

    private void Awake()
    {
        _source = new CancellationTokenSource();
        AllDone = new ManualResetEvent(false);
    }

    private async void Start()
    {
        await Task.Run(() => ListenEvents(_source.Token));
    }

    private void ListenEvents(CancellationToken token)
    {
        Debug.LogError("Error"); //LOG FOR DEV BUILD
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);

        _listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        
        try
        {
            _listener.Bind(localEndPoint);
            _listener.Listen(10);
            
            while (!token.IsCancellationRequested)
            {
                AllDone.Reset();

                _listener.BeginAccept(new AsyncCallback(AcceptCallback), _listener);

                while (!token.IsCancellationRequested)
                {
                    if (AllDone.WaitOne(Waittime))
                    {
                        break;
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);
        
        AllDone.Set();

        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }

    private void ReadCallback(IAsyncResult ar)
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int read = handler.EndReceive(ar);

        if (read > 0)
        {
            _data = Encoding.ASCII.GetString(state.buffer, 0, read);
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback),
                state);
        }
        else
        {
            if (_data.Length > 1)
            {
                MioData = JsonConvert.DeserializeObject<MioData>(_data);
                if(droneFootballController)
                    SetDroneFootballData(MioData, droneFootballController);
                else if(droneRaceController)
                    SetDroneRaceData(MioData, droneRaceController);
            }
            handler.Close();
        }
    }

    private void SetDroneFootballData(MioData data, DroneFootballController drone)
    {
        drone.throttle = data.LeftMio.X / 1000f;
        drone.pedals = data.LeftMio.Y / 1000f;
        drone.cyclic.x = data.RightMio.X / 1000f;
        drone.cyclic.y = data.RightMio.Y / 1000f;
    }
    
    private void SetDroneRaceData(MioData data, DroneRaceController drone)
    {
        drone.throttle = data.LeftMio.X / 1000f;
        drone.pedals = data.LeftMio.Y / 1000f;
        drone.cyclic.x = data.RightMio.X / 1000f;
        drone.cyclic.y = data.RightMio.Y / 1000f;
    }

    private void OnDestroy()
    {
        _source.Cancel();
        _source.Dispose();
    }

    public class StateObject
    {
        public Socket workSocket = null;
        public const int BufferSize = 1024;
        public byte[] buffer = new byte[BufferSize];
    }
}

内容的提问来源于stack exchange,提问作者Калашников Ян

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:32:04