创建连接
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