技术标签: c# websocket C# .net 异步操作 WebSocket
ClientWebSocket
这里用到的核心代码就是ClientWebSocket
类。提供用于连接到WebSocket服务的客户端。
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异步编程。
文章浏览阅读5.9k次,点赞9次,收藏16次。解决了在simulink中使用s-function遇到的报错:State derivatives returned by S-function 'demo' in 'test/S-Function' during flag=1 call must be a real vector of length 2 _state derivatives returned by s-function 'pmsm' in 'ipmsm/ipmsm/s-function1
文章浏览阅读3.1k次。1. 打开配置文件Mac 如下图2. 在文件内部添加这段文字,就可以了:"update_check":false _mac sublime text 取消更新提示
文章浏览阅读548次,点赞10次,收藏6次。Linux系统下DNS配置指南_linux 服务器修改网络dns
文章浏览阅读779次,点赞19次,收藏24次。springboot微信小程序的小疾病问诊服务系统的设计与实现。springboot基于spring的物业管理系统的设计与实现。springboot基于Java的高校学生请假系统。ssm基于Android的购物商场APP设计与实现。springboot基于微信小程序的智慧校园系统。ssm基于Android的英语词典的设计与开发。ssm基于SSM+Vue的学生实践管理平台开发。ssm基于android的企业员工考勤系统。ssm基于web的暗香小店系统的设计与实现。ssm基于Web的高等学校公费医疗管理系统。
文章浏览阅读2.3w次,点赞15次,收藏63次。hover属性用不同的书写方式,来改变不同关系的元素样式。元素:hover 表示聚焦后改变自己元素:hover 元素 表示聚焦后改变其子元素元素:hover + 元素 表示聚焦后改变其指定的“亲兄弟”(条件是该兄弟元素与其相邻)元素元素:hover ~ 元素 表示聚焦后改变其指定的兄弟元素,两个元素相不相邻都行。示例:.first:hover {color: white;}/* 聚焦我改变自己 */.three:hover .three-son {font-size: 20px._css hover的用法
文章浏览阅读6k次,点赞3次,收藏15次。coursera-斯坦福-机器学习-吴恩达-第8周笔记-无监督学习coursera-斯坦福-机器学习-吴恩达-第8周笔记-无监督学习1聚类算法clutering1聚类算法简介2K-means21kmeans的目标函数22随机初始化23选择类别数3考试quiz维数约减 dimensionality reduction1数据压缩2数据可视化3维度约简-主成分分析法PCA1 PCA_pca反向压缩
文章浏览阅读3.5k次。一、Bootstrap 弹出框弹出框控件类似于提示框,它在鼠标点击到元素后显示,与提示框不同的是它可以显示更多的内容。注意: 弹出框要写在 jQuery 的初始化代码里: 然后在指定的元素上调用 popover() 方法。1.1 基本弹出框通过向元素添加 data-toggle=“popover” 来来创建弹出框。title 属性的内容为弹出框的标题,data-content 属性..._bootstrap 弹出框
文章浏览阅读226次,点赞2次,收藏3次。本项目设计了一款可以触摸控制的天气显示器。主要由Wemos D1 Mini Pro和TFT显示屏组成,利用Wemos D1 Mini Pro作为设备的主控芯片,发出Wi-Fi信号并接收相应指令,通过调用API将接收到的信息传输到TFT显示屏,TFT显示屏将接收到的信息显示出来。该天气显示器实现对所在地区当前的时间与日期;当日的天气信息,如温度、压力、湿度、降雨量;七天的未来预测等功能的显示。设计采用Wemos D1 Mini Pro,利用API将实时获取的天气信息,通过TFT显示屏显示出来。_arduino wemos d1 mini
文章浏览阅读653次。public void initDiffDisplay() { try { DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); Display[] presentationDisplays = displayManager.getDisplays(); if (presentationDi._android service 检测是否双屏
文章浏览阅读530次,点赞23次,收藏10次。springboot+mybatisplus+mysql 用户端 uniapp(vue语法)管理后台 vue+elementUi。后台服务 springboot+mybatisplus+mysql。一、我们技术使用JAVA后台服务 前后端分离。管理后台 vue+elementUi。用户端 uniapp(vue语法)适配小程序+H5+公众号。私信客服获取演示地址。私信客服获取演示地址。
文章浏览阅读3.3k次,点赞3次,收藏5次。# -*- coding: UTF-8 -*-year = int(input("输入一个年份:"))if year % 100 == 0: if year % 400 == 0: print('%d年是闰年' % year) else: print('%d年不是闰年' % year)else: if year % 4 == 0: print('%d年是闰年' % year) else: print('%d_判断闰年的python程序直接输入一个代表年份的正整数
文章浏览阅读987次,点赞20次,收藏19次。偏微分方程PDE图像去噪(含SNR)完整的代码,方可运行;可提供运行操作视频!适合小白!_pdnet 深度学习 偏微分方程 去噪