public override void ExecuteCommand(ChatSession session, StringRequestInfo requestInfo) { var result = new MsgInfo(MsgType.JOIN_RESULT); var frame = MsgFrame.Parse(requestInfo.Body); var msg = MsgInfo.FromFrame(new[] { frame }); var username = msg.FromUser; // 用户未输入昵称 if (string.IsNullOrWhiteSpace(username)) { result.Success = false; result.Message = "Please enter your Nickname."; MsgUtil.Send(session, result); return; } var sessions = session.AppServer.GetSessions(_ => !string.IsNullOrWhiteSpace(_.UserName)).ToList(); // 昵称已经存在 if (sessions.Any(_ => _.UserName.Equals(username, StringComparison.OrdinalIgnoreCase))) { result.Success = false; result.Message = "Nickname [" + username + "] exists, please get another one."; MsgUtil.Send(session, result); return; } // 昵称不存在,可以加入聊天 session.UserName = username; // 返回当前的用户列表 var users = sessions.Where(sess => sess.SessionID != session.SessionID) .Select(sess => sess.UserName); result.Data = string.Join(",", users).ToBin(); MsgUtil.Send(session, result); // 通知其它用户 MsgUtil.SendAll(session, new MsgInfo(MsgType.NEW_JOIN) { FromUser = session.UserName }); }
private void client_DataReceived(object sender, DataEventArgs e) { // 这里要注意: // e.Length 是实际数据的长度 // 如果直接使用 Encoding.UTF8.GetString(e.Data) // 会读取到填充的\0字符,这会引起不可预知的意外 var data = buffer + Encoding.UTF8.GetString(e.Data, 0, e.Length); buffer.Clear(); var temp = data.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); switch (temp.Length) { case 0: return; case 1: data = temp[0]; break; default: data = temp[0]; buffer.Append(temp[1]); break; } var frame = MsgFrame.Parse(data); if (Cache.Check(frame)) { return; } var msg = MsgInfo.FromFrame(Cache.Get(frame.Id)); switch (msg.Type) { case MsgType.JOIN_RESULT: // 加入结果 // 加入成功 if (msg.Success) { // 更新标题 Text = "Client - " + tName.Text; if (msg.Data != null && msg.Data.Length != 0) { list.Items.Clear(); var onlineusers = msg.Data.ToStr().Split(",".ToArray()); foreach (var item in onlineusers) { AddUser(item); } } AppendNotify("U can enjoy the chat now"); } else { client.Close(); bConnect.Text = "Connect"; AppendNotify(msg.Message); } break; case MsgType.NEW_JOIN: // 有新用户加入 AppendNotify(string.Format("User {0} join", msg.FromUser)); AddUser(msg.FromUser); break; case MsgType.SEND_RESULT: // 发送消息结果 if (!msg.Success) { AppendNotify(msg.Message); } break; case MsgType.MSG: // 收到消息 AppendMsg(msg, false); break; case MsgType.QUIT: // 用户退出 AppendNotify(string.Format("User {0} leave", msg.FromUser)); RemoveUser(msg.FromUser); break; } }