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

相关推荐
软件黑马王子6 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
不吃斋的和尚11 小时前
Unity中一个节点实现植物动态(Shader)
unity·游戏引擎
程序猿多布12 小时前
Unity 位图字体
unity
千年奇葩14 小时前
Unity shader glsl着色器特效之 模拟海面海浪效果
unity·游戏引擎·着色器
太妃糖耶16 小时前
Unity摄像机与灯光相关知识
unity·游戏引擎
007_rbq16 小时前
XUnity.AutoTranslator-Gemini——调用Google的Gemini API, 实现Unity游戏中日文文本的自动翻译
人工智能·python·游戏·机器学习·unity·github·机器翻译
万兴丶17 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
软件黑马王子1 天前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#
龚子亦1 天前
Unity结合Vuforia虚拟按键实现AR机械仿真动画效果
unity·游戏引擎·ar·数字孪生·虚拟仿真
程序猿多布2 天前
Unity Excel导表工具转Lua文件
unity·excel