bool isNext = true;
while (isNext)
{
if (socket.State == WebSocketState.Open)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
#region 关闭Socket处理,删除连接池
if (socket.State != WebSocketState.Open)//连接关闭
{
if (_userPool.Find(c => c.User_name == user_name) != null)
_userPool.Remove(_userPool.Find(c => c.User_name == user_name));//删除连接池
//广播当前在线的用户 我下线了
foreach (var item in _userPool)
{
MessageModel offline = new MessageModel()
{
Aim = item.User_name,
Contents = user_name + "下线了",
Source = sourcePool.User_name,
Status = 1
};
await item.Socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonHelper.ObjectToJson(offline))), WebSocketMessageType.Text, true, CancellationToken.None);
}
break;
}
#endregion
#region 如果连接没有关闭,处理发送过来的消息
MessageModel model=new MessageModel();
int messageCount = result.Count;
string messageStr= Encoding.UTF8.GetString(buffer.Array, 0, messageCount);
model = JsonHelper.JsonToObject<MessageModel>(messageStr);//这个是解析好的 消息
//发送消息到每个客户端
foreach (var item in _userPool)
{
await item.Socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonHelper.ObjectToJson(model))), WebSocketMessageType.Text, true, CancellationToken.None);
}
#endregion
}
}