参考 https://www.cnblogs.com/Jason-c/p/11117002.html
https://segmentfault.com/a/1190000014582485?utm_source=tag-newest
微软官方文档 ClientWebSocket类
WebSocket客户端,用来发送或接收WebSocket消息。如果你的服务所在的域是HTTPS的,那么使用的WebSocket协议也必须是wss而不是ws
示例:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Text;
using UnityEngine;
/// <summary>
/// 封装WebSocket
/// </summary>
public sealed class WebSocketWrap
{
//连接状态改变
public Action<WebSocketState> OnWebSocketState;
//连接失败
public Action OnConnectError;
//数据返回
public Action<string> OnMessage;
private ClientWebSocket ws;
private CancellationToken ct;
// 是否已连接上
public bool IsOpen
{
get
{
if (ws == null)
return false;
return ws.State == WebSocketState.Open;
}
}
// 是否正在连接中...
public bool IsConnecting
{
get
{
if (ws == null)
return false;
return ws.State == WebSocketState.Connecting;
}
}
//uri: 例如 ws://192.168.1.155:8800
public async void Connect(string uri)
{
try
{
if (ws != null &&
(ws.State == WebSocketState.Connecting ||
ws.State == WebSocketState.Open))
return;
Debug.LogFormat("[WebSocket] 开始连接 {0}", uri);
ws = new ClientWebSocket();
ct = new CancellationToken();
Uri url = new Uri(uri);
await ws.ConnectAsync(url, ct);
if (OnWebSocketState != null)
OnWebSocketState(ws.State);
int capacity = 1024*1024;//缓冲区大小 1kb
byte[] array = new byte[capacity];
var buffer = new ArraySegment<byte>(array);
List<byte> receiveList = new List<byte>();
WebSocketReceiveResult result;
while (true)
{
receiveList.Clear();
do
{
//接受数据
result = await ws.ReceiveAsync(buffer, CancellationToken.None);
//读取数据块
byte[] block = new byte[result.Count];
Buffer.BlockCopy(buffer.Array, 0, block, 0, block.Length);
receiveList.AddRange(block);
} while (!result.EndOfMessage);//判断消息是否接收完毕
byte[] bytes = receiveList.ToArray();
string str = Encoding.UTF8.GetString(bytes);
if (OnMessage != null)
OnMessage(str);
}
}
catch (Exception ex)
{
Debug.LogErrorFormat("[WebSocket] {0}\nCloseStatus: {1}\nCloseStatusDescription: {2}", ex.Message, ws.CloseStatus, ws.CloseStatusDescription);
if (OnConnectError != null)
OnConnectError();
}
finally
{
if (ws != null)
ws.Dispose();
ws = null;
Debug.Log("WebSocket Dispose!");
}
}
// 发送心跳
public void SendHeartBeat()
{
if (ws == null || ws.State != WebSocketState.Open)
return;
Debug.Log("发送心跳包");
ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("{\"id\":1000}")), WebSocketMessageType.Text, true, ct);
}
// 发送数据
public void Send(int id, string data)
{
if (ws == null || ws.State != WebSocketState.Open)
{
Debug.LogErrorFormat("[WebSocket] 发送数据失败,未连接上服务器。");
return;
}
Debug.LogFormat("send protocol: {0}", id);
WebDataStructure wds = new WebDataStructure();
wds.id = id;
wds.data = data;
string json = JsonUtility.ToJson(wds);
ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(json)), WebSocketMessageType.Text, true, ct);
}
//中止WebSocket连接并取消任何挂起的IO操作
public void Abort()
{
if (ws == null)
return;
ws.Abort();
}
}
public class WebDataStructure
{
public int id;
public string data; //json串
}