HTML5描述NET
Core描述
readyState 只读属性 readyState 表⽰连接状态,可以是以下值:
0 - 表⽰连接尚未建⽴。
1 - 表⽰连接已建⽴,可以进⾏通信。
2 - 表⽰连接正在进⾏关闭。
3 - 表⽰连接已经关闭或者连接不能打开。
State(点击看官⽅⽂
档)
bufferedAmount只读属性 bufferedAmount 已被 send() 放⼊正在队列中等待传输,但是还没有发出的
UTF-8 ⽂本字节数。
-
-----⽆此属性
HTML5描述NET Core描述
onopen连接建⽴时触发OnOpen连接建⽴时触发
onmessage客户端接收服务端数据时触发OnMessage客户端接收服务端数据时触发(暂时只⽀持⽂本消息)
onerror通信发⽣错误时触发OnError 通信发⽣错误时触发
(如果处理消息中有错误事件没有处理,这⾥也会抛出并断开链接)
onclose连接关闭时触发OnClose连接关闭时触发
HTML5描述NET Core描述
send()使⽤连接发送数
据bool Send(string mess)
bool Send(byte[] bytes)
使⽤连接发送⽂本消息
使⽤连接发送字节消息
返回:是否尝试了发送
close()关闭连接void Close()
void Close(WebSocketCloseStatus closeStatus, string
statusDescription)
关闭连接(关闭原因为⽤户⼿动关
闭)
关闭连接(⾃定义关闭原因)
C#NetCore使⽤ClientWebSocket实现WebSocket客户端C# 使⽤ ClientWebSocket 实现 WebSocket 客户端
C# Net Core 使⽤ ClientWebSocket 实现 WebSocket 客户端
Net Core 使⽤ ClientWebSocket 实现 WebSocket 客户端
我们模仿HTML5的实现⽅式来重写⼀个C#类
WebSocket 属性
WebSocket 事件
WebSocket ⽅法
代码如下:
创建⽂件WSocketClientHelp.cs:
复制如下代码进去
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YingCaiEdu.Common.HttpHelp
{
public class WSocketClientHelp
{
ClientWebSocket ws = null;
Uri uri = null;
bool isUserClose = false;//是否最后由⽤户⼿动关闭
/
// <summary>
/// WebSocket状态
/// </summary>
public WebSocketState? State { get => ws?.State; }
/// <summary>
/// 包含⼀个数据的事件
/// </summary>
public delegate void MessageEventHandler(object sender, string data);
public delegate void ErrorEventHandler(object sender, Exception ex);
/// <summary>
/// 连接建⽴时触发
/
// </summary>
public event EventHandler OnOpen;
/// <summary>
/// 客户端接收服务端数据时触发
/// </summary>
public event MessageEventHandler OnMessage;
/// <summary>
/// 通信发⽣错误时触发
/// </summary>
public event ErrorEventHandler OnError;
/// <summary>
/
// 连接关闭时触发
/// </summary>
public event EventHandler OnClose;
public WSocketClientHelp(string wsUrl)
{
uri = new Uri(wsUrl);
ws = new ClientWebSocket();
}
/// <summary>
/// 打开链接
/// </summary>
public void Open()
{
Task.Run(async () =>
{
if (ws.State == WebSocketState.Connecting || ws.State == WebSocketState.Open)
return;
string netErr = string.Empty;
try
{
//初始化链接
isUserClose = false;
ws = new ClientWebSocket();
await ws.ConnectAsync(uri, CancellationToken.None);
if (OnOpen != null)
OnOpen(ws, new EventArgs());
Send("放映");
//全部消息容器
List<byte> bs = new List<byte>();
//缓冲区
var buffer = new byte[1024 * 4];
//监听Socket信息
WebSocketReceiveResult result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); //是否关闭
while (!result.CloseStatus.HasValue)
{
//⽂本消息
if (result.MessageType == WebSocketMessageType.Text)
{
bs.AddRange(buffer.Take(result.Count));
//消息是否已接收完全
if (result.EndOfMessage)
{
//发送过来的消息
string userMsg = Encoding.UTF8.GetString(bs.ToArray(), 0, bs.Count);
if (OnMessage != null)
OnMessage(ws, userMsg);
//清空消息容器
bs = new List<byte>();
}
}
//继续监听Socket信息
result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
////关闭WebSocket(服务端发起)
//await ws.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
catch (Exception ex)
{
netErr = " .Net发⽣错误" + ex.Message;
if (OnError != null)
OnError(ws, ex);
//if (ws != null && ws.State == WebSocketState.Open)
// //关闭WebSocket(客户端发起)
// await ws.CloseAsync(WebSocketCloseStatus.Empty, ex.Message, CancellationToken.None);
}
finally
{
if (!isUserClose)
Close(ws.CloseStatus.Value, ws.CloseStatusDescription + netErr);
}
});
}
/// <summary>
/// 使⽤连接发送⽂本消息
/// </summary>
/// <param name="ws"></param>
/// <param name="mess"></param>
/
// <returns>是否尝试了发送</returns>
public bool Send(string mess)
{
if (ws.State != WebSocketState.Open)
return false;
Task.Run(async () =>
{
var replyMess = Encoding.UTF8.GetBytes(mess);
//发送消息
await ws.SendAsync(new ArraySegment<byte>(replyMess), WebSocketMessageType.Text, true, CancellationToken.None); });
return true;
}
/// <summary>
/// 使⽤连接发送字节消息
/// </summary>
/// <param name="ws"></param>
/// <param name="mess"></param>
/// <returns>是否尝试了发送</returns>
public bool Send(byte[] bytes)
{
if (ws.State != WebSocketState.Open)
return false;
Task.Run(async () =>
{
//发送消息
await ws.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Binary, true, CancellationToken.None); });
return true;
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
isUserClose = true;
Close(WebSocketCloseStatus.NormalClosure, "⽤户⼿动关闭");
}
public void Close(WebSocketCloseStatus closeStatus, string statusDescription)
{
Task.Run(async () =>
{
try
{
//关闭WebSocket(客户端发起)
await ws.CloseAsync(closeStatus, statusDescription, CancellationToken.None);
}
catch (Exception ex)
{
}
ws.Abort();
ws.Dispose();
if (OnClose != null)
OnClose(ws, new EventArgs());
});
}
}
}
使⽤⽅法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YingCaiEdu.Common.HttpHelp;
namespace YingCaiEdu.PPT.VstoPpt
{
public class PptSocket
{
private static PptSocket _this;
public static PptSocket This
{
get
{
if (_this == null)
{
_this = new PptSocket();
}
return _this;
}
}
public WSocketClientHelp wSocketClient = new WSocketClientHelp("wss://baidu?user=ppt"); public void Go()
{websocket和socket
wSocketClient.OnOpen -= WSocketClient_OnOpen;
wSocketClient.OnMessage -= WSocketClient_OnMessage;
wSocketClient.OnClose -= WSocketClient_OnClose;
wSocketClient.OnError -= WSocketClient_OnError;
wSocketClient.OnOpen += WSocketClient_OnOpen;
wSocketClient.OnMessage += WSocketClient_OnMessage;
wSocketClient.OnClose += WSocketClient_OnClose;
wSocketClient.OnError += WSocketClient_OnError;
wSocketClient.Open();
}
private void WSocketClient_OnError(object sender, Exception ex)
{
}
private void WSocketClient_OnClose(object sender, EventArgs e)
{
}
private void WSocketClient_OnMessage(object sender, string data) {
//处理的消息错误将会忽略
try
{
if (data.Contains("放映"))
{
PptVstoApp.GetPptApp.SlideShowFromCurrent();
}
}
catch (Exception ex)
{
}
}
private void WSocketClient_OnOpen(object sender, EventArgs e) {
}
}
}
完成
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论