小工具知识网

当前位置: 首页 > 行业知识 > unity 连接WebSocket

行业知识

unity 连接WebSocket

2026-10-31 18:51:31 来源:互联网转载

unity 连接需要联网的WebSocket

using System;using System.Collections.Generic;using System.Net;using System.Net.Sockets;using System.Net.WebSockets;using System.Text;using System.Threading;using System.Threading.Tasks;using Newtonsoft.Json;using UnityEngine;//SingletonManager: 继承MonoBehaviour的单例(也可以直接继承MonoBehaviour)public class WebNetworkClient  : SingletonManager    {    //服务器的地址    public string url = "ws://192.168.1.206:6070";    ClientWebSocket Socket;    CancellationToken ct;    //启动WebSocket(有需要在其他脚本启动/可以增加一个Awake在这个脚本调用)    public async void WebSocket()    {        try        {            Socket = new ClientWebSocket();            ct = new CancellationToken();            //添加header            //Socket.Options.SetRequestHeader("Authorization", token);            await Socket.ConnectAsync(new Uri(url), ct);            Debug.Log("开启雷达监听");            await Socket.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes("Token=" + UnityHttpHelper.Ins.api_token)), WebSocketMessageType.Text, true, ct); //发送第一条数据            while (true)            {                var result = new byte[10240];                await Socket.ReceiveAsync(new ArraySegment(result), ct);//接受数据                ReceiveAsyncInfo(Encoding.UTF8.GetString(result, 0, result.Length));            }        }        catch (Exception ex)        {            Debug.Log(ex.Message);        }    }    void ReceiveAsyncInfo(string info)    {        //收到服务器返回的数据        //Debug.Log(info);           }    private void OnApplicationQuit()    {        //应用关闭 主动断开链接        Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "拜拜", ct);    }}
()()

上一篇:保姆级教程,轻松下载小郑完整版!

下一篇:SpringCloud之SSO单点登录-基于Gateway和OAuth2的跨系统统一认证和鉴权详解