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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值