WebSocket接收完整消息
//拓展方法(静态类中)
public static async System.Threading.Tasks.Task<MsgInfo> ReceiveMsg(this System.Net.WebSockets.WebSocket ws, int Capacity = 1024 * 1024 * 1)
{
//容器,至多只能保存初始化大小的信息
//Capacity必须大于0,否者代码在执行到这里,前端websocket会断开
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[Capacity]);
//初始定义化消息结果类,主要是将result.EndOfMessage设为false
WebSocketReceiveResult result = new WebSocketReceiveResult(0, WebSocketMessageType.Binary, false);
//用于保存完整消息的所有片段
List<byte[]> Message = new List<byte[]>();
//消息未完全接收,用于接收完整的消息
while (!result.EndOfMessage)
{
//接收消息
result = await ws.ReceiveAsync(buffer, System.Threading.CancellationToken.None);
Message.Add(buffer.Take(result.Count).ToArray());//保存消息片段
}
byte[] temp = new byte[0];//储存完整消息的容器
Message.ForEach(u => temp = temp.Concat(u).ToArray());//将所有消息片段进行整合(提取实际数据)
buffer = new ArraySegment<byte>(temp);//将完整消息保存到容器中(buffer)
//MsgInfo,自写类
return new MsgInfo() { Buffer = buffer, Result = result };
}
希望对正在学习WebSocket的你有所帮助!