ClientWebSocket
这里用到的核心代码就是ClientWebSocket 类。提供用于连接到WebSocket服务的客户端。
- 程序集:System.Net.WebSockets.Client.dll;
- 命名空间:System.Net.WebSockets;
- 继承:Object—>WebSocket—>ClientWebSocke;
csharp public sealed class ClientWebSocket : System.Net.WebSockets.WebSocket
属性
属性 | 作用 |
---|
CloseStatus | 获取在ClientWebSocket实例上启动关闭握手的原因。 | CloseStatusDescription | 获取对关闭ClientWebSocket实例的原因的描述。 | Options | 获取ClientWebSocket实例的WebSocket选项。 | State | 获取ClientWebSocket实例的WebSocket状态。 | SubProtocol | 获取ClientWebSocket实例支持的WebSocket子协议。 |
方法
方法 | 作用 |
---|
Abort() | 中止连接并取消任何挂起的IO操作。 | CloseAsync(WebSocketCloseStatus, String, CancellationToken) | 关闭作为异步操作的ClientWebSocket 实例。 | CloseOutputAsync(WebSocketCloseStatus, String, CancellationToken) | 关闭作为异步操作的ClientWebSocket 实例的输出。 | ConnectAsync(Uri, CancellationToken) | 连接到WebSocket服务器以作为异步操作。 | Dispose() | 释放ClientWebSocket 实例使用的非托管资源。 | Equals(Object) | 确定指定对象是否等于当前对象。(继承自Object ) | GetHashCode() | 作为默认哈希函数。(继承自Object ) | GetType() | 获取当前实例的Type 。(继承自Object ) | MemberwiseClone() | 创建当前Object 的浅表副本。(继承自Object ) | ReceiveAsync(ArraySegment<Byte>, CancellationToken) | 将ClientWebSocket 上的数据作为异步操作进行接收。 | ReceiveAsync(Memory<Byte>, CancellationToken) | 将ClientWebSocket 上的数据作为异步操作进行接收。 | SendAsync(ArraySegment<Byte>, WebSocketMessageType, Boolean, CancellationToken) | 以异步操作方式,发送ClientWebSocket 上的数据。 | SendAsync(ReadOnlyMemory<Byte>, WebSocketMessageType, Boolean, CancellationToken) | 以异步操作方式,从只读字节内存范围发送ClientWebSocket 上的数据。 | ToString() | 返回表示当前对象的字符串。(继承自Object ) |
代码
以下是我项目中用到的父类实例,仅供参考:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class WebSocketLink
{
public WebSocketLink(string url)
{
m_uri = new Uri(url);
m_client = new ClientWebSocket();
m_cToken = new CancellationToken();
}
protected readonly Uri m_uri = null;
protected readonly ClientWebSocket m_client = null;
protected readonly CancellationToken m_cToken;
protected WebSocketReceiveResult m_websocketReceiveResult = null;
protected byte[] m_byteArrBuffer = null;
protected string m_result = null;
protected bool Loop { get { return m_client.State == WebSocketState.Open; } }
protected ArraySegment<byte> GetBuffer(byte[] arr)
{
return new ArraySegment<byte>(arr);
}
protected ArraySegment<byte> GetBuffer(string str)
{
return GetBuffer(Encoding.UTF8.GetBytes(str));
}
protected async Task<WebSocketReceiveResult> ReceiveMessage()
{
m_byteArrBuffer = new byte[1024];
WebSocketReceiveResult wsrResult = await m_client.ReceiveAsync(GetBuffer(m_byteArrBuffer), new CancellationToken());
m_result += Encoding.UTF8.GetString(m_byteArrBuffer, 0, wsrResult.Count);
return wsrResult;
}
protected virtual void ParseResult()
{
}
protected virtual void WebSocketError(Exception ex)
{
Debug.LogError(ex.Message + "\n" + ex.StackTrace + "\n" + ex.Source + "\n" + ex.HelpLink);
}
public async void ConnectAuthReceive()
{
try
{
await m_client.ConnectAsync(m_uri, m_cToken);
while (Loop)
{
m_websocketReceiveResult = await ReceiveMessage();
if (m_websocketReceiveResult.EndOfMessage)
{
if (string.IsNullOrEmpty(m_result))
{
break;
}
ParseResult();
}
}
}
catch (Exception ex)
{
WebSocketError(ex);
}
}
public async Task SendRequest(string text)
{
if (m_client.State == WebSocketState.None) { Debug.Log("未建立链接!"); return; }
await m_client.SendAsync(GetBuffer(text), WebSocketMessageType.Text, true, m_cToken);
}
public async void Close()
{
if (m_client.State == WebSocketState.None) { Debug.Log("未建立链接!"); return; }
await m_client.CloseAsync(WebSocketCloseStatus.NormalClosure, "正规闭包", m_cToken);
}
public void Abort()
{
if (m_client.State == WebSocketState.None) { Debug.Log("未建立链接!"); return; }
m_client.Abort();
}
}
async/await
代码中使用的是async/await 的异步编程:C# async/await异步编程。
参考链接
- https://docs.microsoft.com/zh-cn/dotnet/api/system.net.websockets.clientwebsocket?view=net-5.0
- https://www.cnblogs.com/Jason-c/p/11117002.html
- https://blog.csdn.net/weixin_39106746/article/details/104919621
|