public void SendMsg(MsgDOT msgDto) { using (var db = new ChatServiceContext()) { var _user = db.Users.FirstOrDefault(a => a.UserName == msgDto.ToName); if (_user != null) { var _msg = new ChatMessage(); _msg.From = db.Users.First(a => a.UserName == msgDto.FromName).UserId; _msg.To = _user.UserId; _msg.Message = msgDto.Message; _msg.MessageState = (int)MessageState.newMessage; _msg.SendTime = DateTime.Now; db.ChatMessages.Add(_msg); db.SaveChanges(); msgDto.MessageId = _msg.MessageId; msgDto.Time = _msg.SendTime; syncSelf(msgDto); PushMsg(msgDto); } else { string _errorMsg = string.Format("消息“{0}”发送失败:未找到 {1} 。", msgDto.Message, msgDto.ToName); Clients.Caller.sysMsg(_errorMsg); if (log.IsErrorEnabled) { log.Error(_errorMsg); } } } }
/// <summary> /// 发信人其他客户端推送消息 /// </summary> /// <param name="msgDto"><see cref="MsgDOT"/></param> private void syncSelf(MsgDOT msgDto) { var fromIds = onlineUsers.First(a => a.UserName == msgDto.FromName).Connections.Select(a => a.ConnectionId).ToList(); fromIds.Remove(Context.ConnectionId); if (fromIds.Any()) { Clients.Clients(fromIds).showMsg(msgDto); } }
/// <summary> /// 推送消息 /// </summary> /// <param name="msgDto"><see cref="MsgDOT"/></param> private void PushMsg(MsgDOT msgDto) { //发送消息 var _user = onlineUsers.FirstOrDefault(a => a.UserName == msgDto.ToName); if (_user != null) { var toIds = _user.Connections.Select(a => a.ConnectionId).ToList(); if (toIds.Any()) { Clients.Clients(toIds).pushMsg(msgDto); } else { Clients.Caller.sysMsg(string.Format("对方已离线,消息会暂时存储到服务器,TA下次上线会看到 。")); } } else { Clients.Caller.sysMsg(string.Format("对方已离线,消息会暂时存储到服务器,TA下次上线会看到 。")); } }