using Serein.Library.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; namespace Serein.Library.Network.WebSocketCommunication { /// /// 消息处理工具 /// public class MsgHandleUtil { private readonly Channel _msgChannel; /// /// 初始化优先容器 /// /// public MsgHandleUtil(int capacity = 100) { _msgChannel = Channel.CreateBounded(new BoundedChannelOptions(capacity) { FullMode = BoundedChannelFullMode.Wait }); } /// /// 等待消息 /// /// public async Task WaitMsgAsync() { // 检查是否可以读取消息 if (await _msgChannel.Reader.WaitToReadAsync()) { return await _msgChannel.Reader.ReadAsync(); } return null; // 若通道关闭,则返回null } /// /// 写入消息 /// /// 消息内容 /// 是否写入成功 public async Task WriteMsgAsync(string msg) { try { await _msgChannel.Writer.WriteAsync(msg); return true; } catch (ChannelClosedException) { // Channel 已关闭 return false; } } /// /// 尝试关闭通道,停止写入消息 /// public void CloseChannel() { _msgChannel.Writer.Complete(); } } public class SocketExtension { /// /// 发送消息 /// /// /// /// public static async Task SendAsync(WebSocket webSocket, string message) { var buffer = Encoding.UTF8.GetBytes(message); await webSocket.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Text, true, CancellationToken.None); } } }