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 MsgQueueUtil { public ConcurrentQueue Msgs = new ConcurrentQueue(); private readonly Channel _msgChannel; public MsgQueueUtil() { _msgChannel = CreateChannel(); } private Channel CreateChannel() { return Channel.CreateBounded(new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.Wait }); } /// /// 等待消息 /// /// public async Task WaitMsgAsync() { var state = await _msgChannel.Reader.ReadAsync(); return state; } public void WriteMsg(string msg) { //Msgs.Enqueue(msg); Console.WriteLine($"{DateTime.Now}{msg}{Environment.NewLine}"); _ = _msgChannel.Writer.WriteAsync(msg); } public bool TryGetMsg(out string msg) { return Msgs.TryDequeue(out msg); } } 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); } } }