Unity 实现WebSocket 简单通信——客户端

创建连接

复制代码
ClientWebSocket socket = new ClientWebSocket();
string url = $"ws://{ip}:{port}";
bool createUri = Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri);
if (createUri)
{
    var task = socket.ConnectAsync(uri, CancellationToken.None);
    task.Wait(1000);

    if (socket.State == WebSocketState.Open)
    {
        Debug.Log("连接成功!");
    }
}

信息接收

复制代码
byte[] arrry = new byte[1024];
ArraySegment<byte> buffer = new ArraySegment<byte>(arrry);

var task = socket.ReceiveAsync(buffer, CancellationToken.None);
task.Wait(1000);

string msg = Encoding.UTF8.GetString(buffer.Array, 0, task.Result.Count);

信息发送

复制代码
ArraySegment<byte> array = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
var task = socket.SendAsync(array, WebSocketMessageType.Binary, true, CancellationToken.None);
task.Wait(2000);

断开连接

复制代码
var task = socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
task.Wait(2000);

拓展

部分Unity 属性或方法在非主线程中调用出错解决

Unity 解决 "... can only be called from the main thread" 问题_unityexception: find can only be called from the m-CSDN博客文章浏览阅读5.1k次,点赞3次,收藏17次。Unity 解决 "... can only be called from the main thread" 问题_unityexception: find can only be called from the main thread. constructors ahttps://blog.csdn.net/xzqsr2011/article/details/128693150

服务端

基于.Net 框架实现WebSocket 简单通信------服务端-CSDN博客【代码】基于.Net 框架实现WebSocket 简单通信------服务端https://blog.csdn.net/2301_79311694/article/details/139480304

相关推荐
暴走约伯5 小时前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
寂寞的船1 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
寂寞的船2 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
探求虚无3 天前
用 AI 在 Unity 里做一款 RTS:最难的不是生成代码,而是证明它真的能玩
人工智能·unity·游戏引擎
17岁的勇气4 天前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
寂寞的船5 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
寂寞的船7 天前
【Unity知识速递】第8期 IL2CPP 托管堆内存碎片与原生堆交互机制深度解析
unity·游戏引擎·交互
寂寞的船8 天前
【Unity知识速递】第5期 Unity 6.2 深度解析:AI Assistant 登场,World Space UI 与 Sentis 全面升级
人工智能·ui·unity
寂寞的船8 天前
【Unity知识速递】第4期 MCP for Unity:用 AI 自然语言控制编辑器
人工智能·unity·编辑器
淡海水8 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc