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

相关推荐
呆呆敲代码的小Y1 小时前
【Unity 实用工具篇】| UX Tool 工具 快速上手使用,提高日常开发效率
游戏·unity·游戏引擎·游戏程序·ux
世洋Blog1 小时前
Unity开发微信小程序-避开新InputSystem有关坑
unity·微信小程序
简简单单OnlineZuozuo15 小时前
提示架构:设计可靠、确定性的AI系统
人工智能·unity·架构·游戏引擎·基准测试·the stanford ai·儿童
uniGame2 天前
FrameDebugger使用说明
unity·性能优化
心之所向,自强不息2 天前
URP Shader编程规则之Properties
unity
飞浪纪元[FWC–FE]3 天前
【无标题】
unity·游戏引擎
红黑色的圣西罗3 天前
对象池简述
unity·c#
淡海水3 天前
【节点】[Texture2DAsset节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·texture2dasset
向宇it3 天前
【unity游戏开发——网络】unity+PurrNet联机实战,实现一个多人对战类《CS/CSGO》《CF/穿越火线》《PUBG/吃鸡》的FPS射击游戏
游戏·unity·游戏引擎·交互·联机
沉默金鱼4 天前
Unity实用技能-GM命令
unity·游戏引擎