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

相关推荐
future_studio1 小时前
聊聊 Unity(小白专享、熟悉基础编程 ... ...)
unity·游戏引擎
ellis197013 小时前
toLua[六] Examples 05_LuaCoroutine分析
unity
程序员正茂1 天前
Unity3d中Tab控件的实现
ui·unity·tab·控件
三掌柜6662 天前
突破AR视觉交互边界:Unity赋能Rokid AR眼镜实现高精度图像识别与实时跟踪
unity·ar·交互
王维志2 天前
使用Asp.Net WebApi(.net 8)托管Unity WebGL
unity·游戏引擎·webgl
lrh30253 天前
Custom SRP 12 - HDR
3d·unity·srp·render pipeline
霜绛3 天前
Unity:Json笔记——Json文件格式、JsonUtlity序列化和反序列化
学习·unity·json·游戏引擎
TYayyyyy3 天前
unity 事件、委托
unity
L X..3 天前
Unity反射调用 ReactiveProperty<T>(泛型类型)内部方法时崩溃
unity·c#·游戏引擎·.net
向宇it4 天前
【推荐100个unity插件】将您的场景渲染为美丽的冬季风景——Global Snow 2
unity·游戏引擎·风景