C#的WebSocket使用简记
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;
/// <summary>WebSocket链接</summary>
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;
/// <summary>WebSocket客户端对象</summary>
protected readonly ClientWebSocket m_client = null;
protected readonly CancellationToken m_cToken;
/// <summary>接收WebSocket返回的信息数据</summary>
protected WebSocketReceiveResult m_websocketReceiveResult = null;
/// <summary>byte数组,用于接收WebSocket返回的数据</summary>
protected byte[] m_byteArrBuffer = null;
/// <summary>接收WebSocket返回的字符串数据</summary>
protected string m_result = null;
/// <summary>是否循环(链接处于打开状态)</summary>
protected bool Loop { get { return m_client.State == WebSocketState.Open; } }
/// <summary>获取缓冲区的byte数组段</summary>
/// <param name="arr">byte数组内容</param>
/// <returns>结果byte数组段</returns>
protected ArraySegment<byte> GetBuffer(byte[] arr)
{
return new ArraySegment<byte>(arr);
}
/// <summary>获取缓冲区的byte数组段</summary>
/// <param name="str">字符串内容</param>
/// <returns>结果byte数组段</returns>
protected ArraySegment<byte> GetBuffer(string str)
{
return GetBuffer(Encoding.UTF8.GetBytes(str));
}
/// <summary>接收信息</summary>
/// <returns>返回值为WebSocketReceiveResult的Task</returns>
protected async Task<WebSocketReceiveResult> ReceiveMessage()
{
m_byteArrBuffer = new byte[1024];
WebSocketReceiveResult wsrResult = await m_client.ReceiveAsync(GetBuffer(m_byteArrBuffer), new CancellationToken());//接受数据
//Debug.Log(wsrResult.Count + "---" + wsrResult.EndOfMessage + "---" + wsrResult.MessageType);
m_result += Encoding.UTF8.GetString(m_byteArrBuffer, 0, wsrResult.Count);
return wsrResult;
}
/// <summary>解析结果</summary>
protected virtual void ParseResult()
{
}
/// <summary>网络报错</summary>
/// <param name="ex">错误信息</param>
protected virtual void WebSocketError(Exception ex)
{
Debug.LogError(ex.Message + "\n" + ex.StackTrace + "\n" + ex.Source + "\n" + ex.HelpLink);
}
/// <summary>连接、接收</summary>
public async void ConnectAuthReceive()
{
try
{
await m_client.ConnectAsync(m_uri, m_cToken);//连接
while (Loop)
{//遍历接受信息
m_websocketReceiveResult = await ReceiveMessage();
if (m_websocketReceiveResult.EndOfMessage)
{//接收完一条完整信息,解析
//Debug.Log("完整一条信息:" + m_result);
if (string.IsNullOrEmpty(m_result))
{//正规闭包的返回值
break;
}
ParseResult();
}
}
}
catch (Exception ex)
{
WebSocketError(ex);
}
}
/// <summary>发送请求</summary>
/// <param name="text">请求信息内容</param>
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);//发送数据
}
/// <summary>关闭</summary>
public async void Close()
{
if (m_client.State == WebSocketState.None) { Debug.Log("未建立链接!"); return; }
await m_client.CloseAsync(WebSocketCloseStatus.NormalClosure, "正规闭包", m_cToken);
}
/// <summary>终止</summary>
public void Abort()
{
if (m_client.State == WebSocketState.None) { Debug.Log("未建立链接!"); return; }
m_client.Abort();
}
}
async/await
代码中使用的是async/await
的异步编程:C# async/await异步编程。