private void Subscriber() { //〇 客户端和服务器端建立连接时需要将自己的身份ID和服务器ID写到数据库,断开连接时删除记录 //〇 每个服务上线时,根据服务唯一ID在Redis上订阅对应的Topic //① 小明发送给小红的消息先被传输到服务A //② 服务A收到消息从数据库中查到小红所连接的服务器是服务B //③ 服务A将小明的消息转发到Redis中服务B的Topic //④ 服务B收到Redis发来的消息 //⑤ 服务B将消息发送给小红 var serverList = Commont.RedisCommont.StackExchangeRedisHelper.redisClient.GetStringKey <List <string> >("ServerList"); if (serverList == null) { serverList = new List <string>(); } ServerId = "722eb960-93f8-422d-b9bb-cd4b9fa78b59";// Guid.NewGuid().ToString(); if (!serverList.Contains(ServerId)) { serverList.Add(ServerId); foreach (var item in serverList) { RabbitMQProducterHelper.CreateInstance().SetExchangQueueName("ProjectDemo", $"Server_topic_{item}", "topic"); RabbitMQConsumerHelper.CreateInstance().ConsumerLogicDelegate += Commont.WebSocketCommont.WebSocketHelper.ConsumerLogicDel; RabbitMQConsumerHelper.CreateInstance().SetExchangQueueName("ProjectDemo", $"Server_topic_{item}", "topic"); } Commont.RedisCommont.StackExchangeRedisHelper.redisClient.SetStringKey("ServerList", JsonConvert.SerializeObject(serverList));//先用最简单的 } }
/// <summary> /// 监听接收 /// </summary> /// <param name="webSocket"></param> /// <returns></returns> public async static Task ReceiveAsync(WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); while (!webSocket.CloseStatus.HasValue)//连接中 { //【记录发送内容】【点对点】记录数据库,标识,【群聊】群聊信息表,表连接查询没有发送过的,发送过后记录日志 //【点对点通讯】判断是否是本机的客户端,是的话直接发送,不是的话找到对应的路由发过去 //【群聊】找出本机的异步发送,分别找出服务器然后发送 var msgValue = Encoding.Default.GetString(buffer);// var msg = JsonConvert.DeserializeObject <MessageModel>(msgValue); var appServerList = Commont.RedisCommont.StackExchangeRedisHelper.redisClient.GetStringKey <Dictionary <string, string> >("APP-ServerList"); if (appServerList.ContainsKey(msg.TargetId.ToString())) { var host = appServerList.FirstOrDefault(u => u.Key == msg.TargetId.ToString()).Value; RabbitMQProducterHelper.CreateInstance().SendMessage(new ConsumerCmd() { Param = msgValue }); await SendMsgAsync(webSocket, "11111111111");//给自己发送消息 } //重置消息容器 buffer = new byte[1024 * 4]; result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); } #region 断开或者异常退出后操作 lock (obj) { var key = SocketList.Where(c => c.Value.Sk == webSocket).FirstOrDefault().Key ?? ""; if (!string.IsNullOrEmpty(key)) { SocketList.Remove(key); //移除 var appServerList = Commont.RedisCommont.StackExchangeRedisHelper.redisClient.GetStringKey <Dictionary <string, string> >("APP-ServerList"); if (appServerList.ContainsKey(key)) { appServerList.Remove(key); Commont.RedisCommont.StackExchangeRedisHelper.redisClient.SetStringKey("APP-ServerList", JsonConvert.SerializeObject(appServerList)); } } } await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None); #endregion }