Ejemplo n.º 1
0
 private bool TrySendPackage(TransPackage package)
 {
     JsonData jsonToSend = JsonData.Create(package);
     string textToSend = JsonData.ConvertToText(jsonToSend);
     byte[] bytesToSend = Encoding.UTF8.GetBytes(textToSend);
     return TrySendData(bytesToSend);
 }
Ejemplo n.º 2
0
        }                             // 添加消息记录

        private static void DealRecvPackage(TransPackage recvPackage, ref Socket socket, ref byte[] buffer, int size)
        {
            if (recvPackage.PackageType != ConstDef.HeartPackage)
            {
                if (IsFakePackage(recvPackage))
                {
                    DealUnloginUser(recvPackage, socket);
                    return;
                }
                switch (recvPackage.PackageType)
                {
                case ConstDef.ChangeChannelName:
                    ChangeChannelName(recvPackage, socket);
                    break;

                case ConstDef.ReportChannelOnline:
                    ReportChannelOnline(recvPackage, socket);
                    break;

                case ConstDef.AdminCommand:
                    DealAdminCommand(recvPackage, socket);
                    break;

                case ConstDef.ReportTerminalOutput:
                    ReportTerminalOutput(recvPackage, socket);
                    break;

                default:
                    DealNormalPackage(recvPackage, buffer, size);
                    break;
                }
            }
        }      // 处理消息 (主函数
Ejemplo n.º 3
0
        public void SelfClient_ReceivedMsg(System.Net.Sockets.Socket socket, byte[] buffer, int size)
        {
            try
            {
                string recvText = Encoding.UTF8.GetString(buffer, 0, size);
                JsonData[] recvJsons = JsonData.ParseStream(recvText);

                foreach (JsonData per in recvJsons)
                {
                    TransPackage recvPackage = JsonData.ConvertToInstance<TransPackage>(per);
                    DealPackage(recvPackage);
                }

                return;
            }
            catch
            {
                if (partsBuffer == null)
                {
                    partsBuffer = new MemoryStream();
                    partsBuffer.Write(buffer, 0, size);
                }
                else
                {
                    partsBuffer.Write(buffer, 0, size);

                    try
                    {
                        string bufferStr = Encoding.UTF8.GetString(partsBuffer.ToArray());
                        if (JsonData.TryParseStream(bufferStr, out JsonData[] jsons))
Ejemplo n.º 4
0
        private bool TrySendImageMsg(System.Drawing.Image img)
        {
            MemoryStream ms = null;

            try
            {
                ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                TransPackage msg = new TransPackage()
                {
                    Name        = WindowParent.NickName,
                    Content     = Convert.ToBase64String(ms.ToArray()),
                    ClientGuid  = WindowParent.ClientGuid,
                    PackageType = ConstDef.ImageMessage
                };

                return(TrySendPackage(msg));
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
        }                                               // 解释指令

        private static void BoardcastPackage(TransPackage package)
        {
            JsonData jsonData = JsonSerializer.Create(package);
            string   jsonText = JsonSerializer.ConvertToText(jsonData);

            byte[] bytes = Encoding.UTF8.GetBytes(jsonText);
            BoardcastData(bytes, bytes.Length);
        }                                // 广播包
Ejemplo n.º 6
0
        private static void DealAdminCommand(TransPackage recvPackage, Socket socket)
        {
            PrintLine($"{recvPackage.Name} try to execute a command on this server.");
            if (!AdminGuid.Contains(recvPackage.ClientGuid))
            {
                socket.SendTOC(
                    Encoding.UTF8.GetBytes(
                        JsonSerializer.ConvertToText(
                            JsonSerializer.Create(new TransPackage()
                {
                    Name        = "Server",
                    Content     = $"You don't have right to execute command on remote server.",
                    ClientGuid  = "Server",
                    PackageType = ConstDef.NormalMessage
                }))));
            }
            else
            {
                DealCommand(recvPackage.Content);
                socket.SendTOC(
                    Encoding.UTF8.GetBytes(
                        JsonSerializer.ConvertToText(
                            JsonSerializer.Create(new TransPackage()
                {
                    Name        = "Server",
                    Content     = $"Command executed!",
                    ClientGuid  = "Server",
                    PackageType = ConstDef.NormalMessage
                }))));
                int    count   = 0;
                Socket socket1 = socket;
                bool p(string a)
                {
                    count += 1;
                    if (count == 2)
                    {
                        //SafeWriteHook -= p;
                    }
                    socket1.Send(
                        Encoding.UTF8.GetBytes(
                            JsonSerializer.ConvertToText(
                                JsonSerializer.Create(new TransPackage()
                    {
                        Name        = "Server",
                        Content     = $"Return:{a}",
                        ClientGuid  = "Server",
                        PackageType = ConstDef.NormalMessage
                    }))));
                    return(true);
                }

                //SafeWriteHook += p;
            }
        }
Ejemplo n.º 7
0
        }                   // 发送吸引注意力

        private static void Server_RecvedClientMsg(object sender, Socket socket, byte[] buffer, int size)
        {
            string recvStr = Encoding.UTF8.GetString(buffer, 0, size);

            JsonData[] recvJsons = JsonSerializer.ParseStream(recvStr);
            foreach (JsonData recvJson in recvJsons)
            {
                TransPackage recvPackage = JsonSerializer.ConvertToInstance <TransPackage>(recvJson);
                DealRecvPackage(recvPackage, ref socket, ref buffer, size);
            }
        }        // 当收到客户端消息
Ejemplo n.º 8
0
        private bool TrySendTextMsg(string text)
        {
            TransPackage msg = new TransPackage()
            {
                Name        = WindowParent.NickName,
                Content     = text,
                ClientGuid  = WindowParent.ClientGuid,
                PackageType = ConstDef.NormalMessage
            };

            return(TrySendPackage(msg));
        }
Ejemplo n.º 9
0
        private void SendVerification(string content)
        {
            TransPackage package = new TransPackage()
            {
                Name        = WindowParent.NickName,
                Content     = content,
                ClientGuid  = WindowParent.ClientGuid,
                PackageType = ConstDef.Verification
            };

            TrySendPackage(package);
        }
Ejemplo n.º 10
0
 private static void WelcomeUser(TransPackage recvPackage, Socket socket)
 {
     socket.SendTOC(
         Encoding.UTF8.GetBytes(
             JsonSerializer.ConvertToText(
                 JsonSerializer.Create(new TransPackage()
     {
         Name        = "Server(AutoReplay)",
         Content     = $"Welcome!{recvPackage.Name}",
         ClientGuid  = "Server",
         PackageType = ConstDef.NormalMessage
     }))));
 }
Ejemplo n.º 11
0
        private static User CreateUser(TransPackage recvPackage)
        {
            User newuser = new User
            {
                Name         = recvPackage.Name,
                PasswordHash = recvPackage.Content.GetHashCode(),
                Guid         = Guid.NewGuid().ToString()
            };

            UserList.Add(newuser);
            SaveUser(USERJSONPATH);
            return(newuser);
        }
Ejemplo n.º 12
0
 private static void ReportChannelOnline(TransPackage recvPackage, Socket socket)
 {
     socket.SendTOC(
         Encoding.UTF8.GetBytes(
             JsonSerializer.ConvertToText(
                 JsonSerializer.Create(new TransPackage()
     {
         Name        = "Server",
         Content     = $"Online: {clients.Count}, Your IP Address: {((IPEndPoint)socket.RemoteEndPoint).Address}",
         ClientGuid  = "Server",
         PackageType = ConstDef.ReportChannelOnline
     }))));
     Console.ForegroundColor = ConsoleColor.DarkGray;
     PrintLine($"Online Info Req: Sender: {recvPackage.Name}");
 }
Ejemplo n.º 13
0
 private static void ChangeChannelName(TransPackage recvPackage, Socket socket)
 {
     socket.SendTOC(
         Encoding.UTF8.GetBytes(
             JsonSerializer.ConvertToText(
                 JsonSerializer.Create(new TransPackage()
     {
         Name        = "Server",
         Content     = channelName,
         ClientGuid  = "Server",
         PackageType = ConstDef.ChangeChannelName
     }))));
     Console.ForegroundColor = ConsoleColor.DarkGray;
     PrintLine($"Channel Name Req: Sender: {recvPackage.Name}");
 }
Ejemplo n.º 14
0
        }      // 处理消息 (主函数

        private static void DealNormalPackage(TransPackage recvPackage, byte[] buffer, int size)
        {
            BoardcastData(buffer, size);
            AddMessageRecord(buffer, size);
            ConsoleColor oldcolor = Console.ForegroundColor;

            if (recvPackage.Content.Length > 250)
            {
                if (!nocolor)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                PrintLine($"{recvPackage.Name}: {new string(recvPackage.Content.Take(250).ToArray())}......(Length:{recvPackage.Content.Length})");
                if (recvPackage.PackageType == ConstDef.ImageMessage)
                {
                    try
                    {
                        if (!nocolor)
                        {
                            Console.ForegroundColor = ConsoleColor.White;
                        }
                        PrintLine($"{GetThumbnailChar((Bitmap)Image.FromStream(new MemoryStream(Convert.FromBase64String(recvPackage.Content))))}");
                    }
                    catch
                    {
                        PrintLine("Cann't Get Thumbnail Image");
                    }
                }
            }
            else if (recvPackage.Content.Length > 100)
            {
                if (!nocolor)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                PrintLine($"{recvPackage.Name}: {recvPackage.Content}");
            }
            else
            {
                if (!nocolor)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                }
                PrintLine($"{recvPackage.Name}: {recvPackage.Content}");
            }
            Console.ForegroundColor = oldcolor;
        }
Ejemplo n.º 15
0
        private static void ReportTerminalOutput(TransPackage recvPackage, Socket socket)
        {
            PrintLine($"{recvPackage.Name} try to hook terminal on this server.");
            if (!AdminGuid.Contains(recvPackage.ClientGuid))
            {
                socket.SendTOC(
                    Encoding.UTF8.GetBytes(
                        JsonSerializer.ConvertToText(
                            JsonSerializer.Create(new TransPackage()
                {
                    Name        = "Server",
                    Content     = $"You don't have right to hook terminal on remote server.",
                    ClientGuid  = "Server",
                    PackageType = ConstDef.NormalMessage
                }))));
            }
            else
            {
                int    count   = 0;
                int    l       = int.Parse(recvPackage.Content);
                Socket socket1 = socket;
                bool p(string a)
                {
                    count += 1;
                    socket1.SendTOC(
                        Encoding.UTF8.GetBytes(
                            JsonSerializer.ConvertToText(
                                JsonSerializer.Create(new TransPackage()
                    {
                        Name        = "Server",
                        Content     = $"Return:{a}",
                        ClientGuid  = "Server",
                        PackageType = ConstDef.NormalMessage
                    }))));
                    return(true);
                }

                //SafeWriteHook += p;
            }
        }
Ejemplo n.º 16
0
        public void SelfClient_ReceivedMsg(object sender, System.Net.Sockets.Socket socket, byte[] buffer, int size)
        {
            MainChat sender1 = (MainChat)((SocketClient)sender).Tag;

            try
            {
                string     recvText  = Encoding.UTF8.GetString(buffer, 0, size);
                JsonData[] recvJsons = JsonSerializer.ParseStream(recvText);

                foreach (JsonData per in recvJsons)
                {
                    TransPackage recvPackage = JsonSerializer.ConvertToInstance <TransPackage>(per);
                    sender1.DealPackage(recvPackage);
                }

                return;
            }
            catch
            {
                MessageBox.Show("Received wrong data which can't be decoded.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 17
0
        private static void DealCommand(string cmd)
        {
            if (string.IsNullOrWhiteSpace(cmd))
            {
                return;
            }
            if (cmd.StartsWith("/"))
            {
                switch (cmd.ToLower().Substring(0, 5))
                {
                case "/help":

                case "/cusr":
                    string[] args = cmd.Split(" ");
                    UserList.Add(new User()
                    {
                        Guid = Guid.NewGuid().ToString(), PasswordHash = args[2].GetHashCode(), Name = args[1]
                    });
                    SaveUser(USERJSONPATH);
                    break;

                default:
                    break;
                }
            }
            else
            {
                TransPackage msg = new TransPackage()
                {
                    Name        = "Server",
                    Content     = cmd,
                    ClientGuid  = "Server",
                    PackageType = ConstDef.Verification
                };

                BoardcastPackage(msg);
            }
        }                                               // 解释指令
Ejemplo n.º 18
0
        private void DealPackage(TransPackage recvPackage)
        {
            if (recvPackage.PackageType != ConstDef.HeartPackage)
            {
                switch (recvPackage.PackageType)
                {
                case ConstDef.NormalMessage:
                    if (recvPackage.ClientGuid == WindowParent.ClientGuid)
                    {
                        AppendTextMessage(recvPackage.Name, recvPackage.Content, HorizontalAlignment.Right);
                    }
                    else
                    {
                        AppendTextMessage(recvPackage.Name, recvPackage.Content, HorizontalAlignment.Left);
                    }
                    App.Current.Dispatcher.Invoke(() => { ChatScroller.ScrollToBottom(); });
                    break;

                case ConstDef.Verification:
                    AppendAnnouncement(recvPackage.Content);
                    App.Current.Dispatcher.Invoke(() => { ChatScroller.ScrollToBottom(); });
                    break;

                case ConstDef.ImageMessage:
                    if (recvPackage.ClientGuid == WindowParent.ClientGuid)
                    {
                        AppendImageMessage(recvPackage.Name, recvPackage.Content, HorizontalAlignment.Right);
                    }
                    else
                    {
                        AppendImageMessage(recvPackage.Name, recvPackage.Content, HorizontalAlignment.Left);
                    }
                    break;

                case ConstDef.DrawAttention:
                    if (recvPackage.ClientGuid == WindowParent.ClientGuid)
                    {
                        AppendAnnouncement($"Your try to draw others' attention.");
                    }
                    else
                    {
                        AppendAnnouncement($"{recvPackage.Name} try to draw your attention.");
                    }
                    break;

                case ConstDef.ChangeChannelName:
                    SetCurrentChannelName(recvPackage.Content);
                    App.Current.Dispatcher.Invoke(() => { ChatScroller.ScrollToBottom(); });
                    break;

                case ConstDef.ReportChannelOnline:
                    AppendAnnouncement(recvPackage.Content);
                    App.Current.Dispatcher.Invoke(() => { ChatScroller.ScrollToBottom(); });
                    break;

                case ConstDef.Login:
                    WindowParent.ClientGuid = recvPackage.Content;
                    break;

                default:
                    // ( 在规定之外的消息 ) 以后再弄详细处理
                    break;
                }
            }
        }
Ejemplo n.º 19
0
        private static void DealUnloginUser(TransPackage recvPackage, Socket socket)
        {
            if (recvPackage.PackageType == ConstDef.NormalMessage)
            {
                string[] args = recvPackage.Content.Split(' ');
                if (args.Length == 2)
                {
                    switch (args[0])
                    {
                    case "/login":
                        recvPackage.PackageType = ConstDef.Login;
                        recvPackage.Content     = args[1];
                        break;

                    default:
                        SendMustLoginInfo(socket);
                        return;
                    }
                }
                else
                {
                    SendMustLoginInfo(socket);
                    return;
                }
            }
            User user = UserList.Find((u) => u.Name == recvPackage.Name);

            switch (recvPackage.PackageType)
            {
            case ConstDef.Login:
                if (user != null)
                {
                    if (user.PasswordHash == recvPackage.Content.GetHashCode())
                    {
                        socket.SendTOC(
                            Encoding.UTF8.GetBytes(
                                JsonSerializer.ConvertToText(
                                    JsonSerializer.Create(new TransPackage()
                        {
                            Name        = "Server",
                            Content     = user.Guid,
                            ClientGuid  = "Server",
                            PackageType = ConstDef.Login
                        }))));
                        WelcomeUser(recvPackage, socket);
                    }
                    else
                    {
                        SendErrorPasswordNotCorrent(socket);
                    }
                }
                else
                {
                    SendErrorUserDoesntExist(socket);
                }
                break;

            case ConstDef.Register:
                if (user == null)
                {
                    User newuser = CreateUser(recvPackage);
                    socket.SendTOC(
                        Encoding.UTF8.GetBytes(
                            JsonSerializer.ConvertToText(
                                JsonSerializer.Create(new TransPackage()
                    {
                        Name        = "Server",
                        Content     = newuser.Guid,
                        ClientGuid  = "Server",
                        PackageType = ConstDef.Login
                    }))));
                    WelcomeUser(recvPackage, socket);
                }
                else
                {
                    SendErrorUserExisted(socket);
                }
                break;

            default:
                SendMustLoginInfo(socket);
                return;
            }
            return;
        }
Ejemplo n.º 20
0
 private static bool IsFakePackage(TransPackage package)
 {
     return(package.PackageType != 0 && CheckUserGuid(package.ClientGuid, package.Name));
 }