예제 #1
0
        public async Task HandleClientMsg(string msg)
        {
            Console.WriteLine("统一从客户端收到的信息:" + msg);
            Message message = JsonConvert.DeserializeObject <Message>(msg);
            Client  _client = new Client(Context.ConnectionId, message.nick, message.roomno);
            string  path    = $"./ChatLogs/{message.nick}_{message.roomno}.txt";

            switch (message.action)
            {
            case (int)ActionOper.InGroupOPeration:
                int codeStatus = GroupManager.AddToRPD(message.roomno, message.password);
                if (codeStatus == (int)ActionOper.FailJoinGroup)
                {
                    string tipInfo = $"操作有误,请检查房间密码是否有误!";
                    await SendPrivateMessage(Context.UserIdentifier, tipInfo);
                }
                else
                {
                    GroupManager.Add(_client);
                    string inGroupInfo = $"用户 {message.nick} 加入房间 {message.roomno}";
                    FileHelp.CreateFile(path, inGroupInfo);
                    Console.WriteLine(inGroupInfo);
                    await Groups.AddToGroupAsync(Context.ConnectionId, message.roomno);

                    await Clients.Group(message.roomno).SendAsync("ReceiveMessage", inGroupInfo);
                }
                break;

            case (int)ActionOper.OutGroupOperation:
                GroupManager.Remove(_client);
                string outGroupInfo = $"用户 {message.nick} 离开房间 {message.roomno}";
                var    list         = GroupManager.GetClientsInGroup(message.roomno);
                if (list != null)
                {
                    foreach (var item in list)
                    {
                        string _path = $"../../../ChatLogs/{item.nickName}_{message.roomno}.txt";

                        await Task.Factory.StartNew(() =>
                        {
                            FileHelp.AppendToFile(_path, outGroupInfo);
                        });
                    }
                }

                Console.WriteLine(outGroupInfo);
                await Clients.Group(message.roomno).SendAsync("ReceiveMessage", outGroupInfo);

                await Groups.RemoveFromGroupAsync(Context.ConnectionId, message.roomno);

                break;

            case (int)ActionOper.SendGroupOperation:
                string sendGroupInfo = $"{message.nick} : {message.msg}";
                FileHelp.AppendToFile(path, sendGroupInfo);
                Console.WriteLine(sendGroupInfo);
                await Clients.Group(message.roomno).SendAsync("ReceiveMessage", sendGroupInfo);

                break;
            }
            GroupManager.OutputRoomInfo();
        }