C#的WebSocket使用简记

本文详细介绍了C#中`ClientWebSocket`类的使用,包括其属性和方法,如`ConnectAsync`、`ReceiveAsync`和`SendAsync`等。通过`async/await`实现异步操作,提供了一个用于连接、接收和发送WebSocket消息的基础类示例,适用于Unity环境。此外,还提到了错误处理和关闭连接的方法。
摘要由CSDN通过智能技术生成

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异步编程

参考链接

  1. https://docs.microsoft.com/zh-cn/dotnet/api/system.net.websockets.clientwebsocket?view=net-5.0
  2. https://www.cnblogs.com/Jason-c/p/11117002.html
  3. https://blog.csdn.net/weixin_39106746/article/details/104919621
以下是使用C#中的ClientWebSocket类连接WebSocket服务的基本步骤: 1. 引用命名空间System.Net.WebSockets。 2. 创建一个ClientWebSocket实例。 3. 使用ConnectAsync方法连接WebSocket服务。 4. 使用SendAsync方法发送消息到WebSocket服务。 5. 使用ReceiveAsync方法接收WebSocket服务发送的消息。 6. 使用CloseAsync方法关闭WebSocket连接。 下面是一个简单的示例代码: ```csharp using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; public class WebSocketClient { private ClientWebSocket _webSocket; public async Task ConnectAsync(Uri uri) { _webSocket = new ClientWebSocket(); await _webSocket.ConnectAsync(uri, CancellationToken.None); } public async Task SendAsync(string message) { var buffer = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(message)); await _webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } public async Task<string> ReceiveAsync() { var buffer = new ArraySegment<byte>(new byte[1024]); var result = await _webSocket.ReceiveAsync(buffer, CancellationToken.None); return System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count); } public async Task CloseAsync() { await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } ``` 使用示例: ```csharp var client = new WebSocketClient(); await client.ConnectAsync(new Uri("ws://localhost:8080")); await client.SendAsync("Hello, WebSocket!"); var message = await client.ReceiveAsync(); Console.WriteLine(message); await client.CloseAsync(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天富儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值