Пример #1
0
        /// <summary>
        /// Get command from server
        /// </summary>

        public void getFromServer()
        {
            new Task(() =>
            {
                try
                {
                    Console.WriteLine("In getFromServer");
                    NetworkStream stream = m_client.GetStream();
                    BinaryReader reader  = new BinaryReader(stream);
                    while (connectionIsOn)
                    {
                        try
                        {
                            string incomingMsg = reader.ReadString();
                            TCPEventArgs info  = JsonConvert.DeserializeObject <TCPEventArgs>(incomingMsg);
                            Console.WriteLine("Got: " + info.CommandID);
                            Console.WriteLine("Got: " + info.Args);
                            GotTcpMessege?.Invoke(this, info);
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    }
                }
                catch { }
            }).Start();
        }
Пример #2
0
        /// <summary>
        /// 数据接收委托函数
        /// </summary>
        /// <param name="result">传入参数</param>
        protected void DataRec(IAsyncResult result)
        {
            int         length = networkstream.EndRead(result);                         //获取接收数据的长度
            List <byte> data   = new List <byte>();                                     //新建byte数组

            data.AddRange((byte[])result.AsyncState);                                   //获取数据
            data.RemoveRange(length, data.Count - length);                              //根据长度移除无效的数据
            byte[] data2 = new byte[1000];                                              //重新定义接收缓冲
            networkstream.BeginRead(data2, 0, 1000, new AsyncCallback(DataRec), data2); //重新挂起数据的接收等待
            //自定义代码区域,处理数据data
            //for (int i = 0; i < data.Count;i++ )
            //{
            //    Debug.WriteLine(data[i]);
            //}
            Encoding receiveEncoding_ = Encoding.UTF8;
            string   receiveStr       = receiveEncoding_.GetString((byte[])result.AsyncState, 0, length);

            receivedMessage = receiveStr;
            receivedMessageCount++;
            //  Debug.WriteLine(receiveStr);

            TCPEventArgs e = new TCPEventArgs(receiveStr);

            OnReceived(e);

            // receiveStr = Base64Sp.toNormalStr(receiveStr, receiveEncoding_);
            if (length == 0)
            {
                //连接已经关闭
            }
        }
Пример #3
0
        /// <summary>
        /// Handle massage from server (only log messebe)
        /// </summary>
        /// <param name="sender">server</param>
        /// <param name="e">params</param>

        public void HandleMessage(object sender, TCPEventArgs message)
        {
            int commandId = message.CommandID;

            try
            {
                if (commandId.Equals((int)CommandEnum.LogCommand))
                {
                    List <JObject> temp = JsonConvert.DeserializeObject <List <JObject> >(message.Args);
                    foreach (JObject log in temp)
                    {
                        string  logType  = (string)log["logType"];
                        string  logInfo  = (string)log["logInfo"];
                        LogArgs toInsert = new LogArgs(logType, logInfo);
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            AllLogs.Add(toInsert);
                        }));
                    }
                    foreach (var data in AllLogs)
                    {
                        Console.WriteLine(data.logType + " " + data.logInfo);
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("exception: " + e.Message);
            }
        }
Пример #4
0
 protected virtual void OnReceived(TCPEventArgs e)
 {
     if (MessageReceived != null)
     {
         MessageReceived(this, e);
     }
 }
Пример #5
0
 /// <summary>
 /// Handle gotten remove-handler from server
 /// </summary>
 /// <param name="sender">server</param>
 /// <param name="message">config</param>
 public void HandleRemoveMessage(object sender, TCPEventArgs message)
 {
     try
     {
         Listhandlers.Remove(message.Args);
     }
     catch (Exception) { }
 }
Пример #6
0
        private void RaiseDataSentEvent(string remoteClient, Message.MessageResponse msg)
        {
            TCPEventArgs e = new TCPEventArgs();

            e.RemoteClient = remoteClient;
            e.Data         = Utility.GetBytesFromString(msg.MessageData);
            DataSent(this, e);
        }
Пример #7
0
 /// <summary>
 /// Handle gotten config from server
 /// </summary>
 /// <param name="sender">server</param>
 /// <param name="message">config</param>
 public void HandleConfigMessage(object sender, TCPEventArgs message)
 {
     try
     {
         UpdateAppConfig(message);
     }
     catch (Exception) { }
 }
Пример #8
0
        /// <summary>
        /// Send command to server
        /// </summary>
        /// <param name="commandTcp">The command</param>
        public void sendToServer(TCPEventArgs commandTcp)
        {
            if (!connectionIsOn)
            {
                bool result;
                StartConnection(out result);
                connectionIsOn = result;
                if (!connectionIsOn)
                {
                    return;
                }
            }
            try
            {
                NetworkStream stream = m_client.GetStream();
                BinaryWriter  writer = new BinaryWriter(stream);
                BinaryReader  reader = new BinaryReader(stream);
                //Serialize and Send To Server
                string toSend = JsonConvert.SerializeObject(commandTcp);
                m_mutexx.WaitOne();
                writer.Write(toSend);
                writer.Flush();
                m_mutexx.ReleaseMutex();
                //Get from server
                string       incomingMsg = reader.ReadString();
                TCPEventArgs info        = JsonConvert.DeserializeObject <TCPEventArgs>(incomingMsg);
                switch (info.CommandID)
                {
                case (int)CommandEnum.CloseCommand:
                    GotCloseHandlerCommand?.Invoke(this, info);
                    break;

                case (int)CommandEnum.GetConfigCommand:
                    GotConfigCommand?.Invoke(this, info);
                    break;

                case (int)CommandEnum.LogCommand:
                    GotLogCommand?.Invoke(this, info);
                    break;

                default:
                    break;
                }

                EndConnection();
            }
            catch (Exception) { serviceIsOn = 0; }
        }
Пример #9
0
 /// <summary>
 /// Handle gotten logs from server
 /// </summary>
 /// <param name="sender">server</param>
 /// <param name="message">logs list</param>
 public void HandleLogMessage(object sender, TCPEventArgs message)
 {
     try
     {
         List <JObject> temp = JsonConvert.DeserializeObject <List <JObject> >(message.Args);
         AllLogs.Clear();
         foreach (JObject log in temp)
         {
             string  logType  = (string)log["logType"];
             string  logInfo  = (string)log["logInfo"];
             LogArgs toInsert = new LogArgs(logType, logInfo);
             AllLogs.Add(toInsert);
         }
     }
     catch (Exception) { }
 }
Пример #10
0
        /// <summary>
        /// Called when a new log is written. Send it to all clients
        /// </summary>
        /// <param name="e">The log</param>
        /// <param name="sender">not relevant</param>

        public void UpdateClientsNewLog(object sender, MessageRecievedEventArgs e)
        {
            List <JObject> temp       = new List <JObject>();
            JObject        jsonObject = new JObject();

            jsonObject["logType"] = Enum.GetName(typeof(MessageTypeEnum), e.Status);
            jsonObject["logInfo"] = e.Message;
            temp.Add(jsonObject);

            string       args       = JsonConvert.SerializeObject(temp);
            TCPEventArgs toSend     = new TCPEventArgs((int)CommandEnum.LogCommand, args);
            string       serialized = JsonConvert.SerializeObject(toSend);

            //Send it to AllClients
            broadcastAllClients(serialized);
        }
Пример #11
0
 /// <summary>
 /// Send command to server
 /// </summary>
 /// <param name="commandTcp">The command</param>
 public void sendToServer(TCPEventArgs commandTcp)
 {
     new Task(() =>
     {
         try
         {
             Console.WriteLine("In sendToServer " + commandTcp.CommandID);
             NetworkStream stream = m_client.GetStream();
             BinaryWriter writer  = new BinaryWriter(stream);
             //Serialize and Send To Server
             string toSend = JsonConvert.SerializeObject(commandTcp);
             m_mutexx.WaitOne();
             writer.Write(toSend);
             writer.Flush();
             m_mutexx.ReleaseMutex();
         }
         catch (Exception) { }
     }).Start();
 }
Пример #12
0
        /// <summary>
        /// Update properties according to the config from server
        /// </summary>
        /// <param name="config">The config that had gotten from server</param>


        public void UpdateAppConfig(TCPEventArgs config)
        {
            string        information = config.Args;
            JObject       manager     = JObject.Parse(information);
            string        str         = (string)manager["handlerPaths"];
            List <string> str2        = JsonConvert.DeserializeObject <List <string> >(str);

            ThumbnailSize   = (manager["thumbnailSize"]).ToString();
            OutputDirectory = (string)manager["outputDir"];
            LogName         = (string)manager["logName"];
            SourceName      = (string)manager["eventSourceName"];

            //This type of CollectionView does not support changes to its SourceCollection
            //from a thread different from the Dispatcher thread.
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                foreach (string handler in str2)
                {
                    Listhandlers.Add(handler);
                }
            }));
        }
Пример #13
0
        /// <summary>
        /// Update properties according to the config from server
        /// </summary>
        /// <param name="config">The config that had gotten from server</param>
        public void UpdateAppConfig(TCPEventArgs config)
        {
            try
            {
                string        information = config.Args;
                JObject       manager     = JObject.Parse(information);
                string        str         = (string)manager["handlerPaths"];
                List <string> str2        = JsonConvert.DeserializeObject <List <string> >(str);
                ThumbnailSize   = (manager["thumbnailSize"]).ToString();
                OutputDirectory = (string)manager["outputDir"];
                LogName         = (string)manager["logName"];
                SourceName      = (string)manager["eventSourceName"];

                foreach (string handler in str2)
                {
                    Listhandlers.Add(handler);
                }
                alreadyGotConfig = true;
            }
            catch
            {
            }
        }
Пример #14
0
        /// <summary>
        /// Ask for appconfig from server
        /// </summary>

        public string getAppConfig()
        {
            try
            {
                NetworkStream stream     = m_client.GetStream();
                BinaryReader  reader     = new BinaryReader(stream);
                BinaryWriter  writer     = new BinaryWriter(stream);
                TCPEventArgs  commandTcp = new TCPEventArgs((int)CommandEnum.GetConfigCommand, null);

                string toSend = JsonConvert.SerializeObject(commandTcp);
                m_mutexx.WaitOne();
                writer.Write(toSend);
                m_mutexx.ReleaseMutex();
                string result2 = reader.ReadString();

                Console.WriteLine(result2);
                return(result2);
            }
            catch (Exception)
            {
                return("Coldn't get app config");
            }
        }
Пример #15
0
        /// <summary>
        /// Handle massage from server (not log message)
        /// </summary>
        /// <param name="sender">server</param>
        /// <param name="e">params</param>

        public void HandleMessage(object sender, TCPEventArgs message)
        {
            int commandId = message.CommandID;

            Console.WriteLine("Id: " + message.CommandID);
            Console.WriteLine("Path: " + message.Args);
            try
            {
                switch (commandId)
                {
                case (int)CommandEnum.CloseCommand:
                    try {
                        App.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            Listhandlers.Remove(message.Args);
                        }));
                    } catch (Exception e)
                    {
                        Console.WriteLine(e.Data);
                        Console.WriteLine("Couldn't remove handler " + message.Args);
                    }
                    break;

                case (int)CommandEnum.GetConfigCommand:
                    UpdateAppConfig(message);
                    break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #16
0
        private void WCMessageArrived(TCP.WorkerClient sender, byte[] b, int len)
        {
            TCPEventArgs e = new TCPEventArgs();

            e.RemoteClient = sender.ClientIP();

            e.Data = new byte[len];

            DataArrived(this, e);

            Array.Copy(b, 0, e.Data, 0, len);

            Message.Message msg = new Message.Message(b);

            Logger.MajorVerbose("Client: " + sender.ClientIP() + System.Environment.NewLine + "Request: " + msg.MessageData);
            try
            {
                Logger.MajorDebug("Parsing header and code of message " + msg.MessageData + "...");
                string messageHeader = msg.GetSubstring(HeaderLength);

                msg.AdvanceIndex(HeaderLength);

                string commandCode = msg.GetSubstring(2);

                msg.AdvanceIndex(2);

                CommandCalled(this, commandCode);

                CommandClass CC = CE.GetLoadedCommand(commandCode);

                if (CC == null)
                {
                    Logger.MajorError("No implementor for " + commandCode + "." + System.Environment.NewLine + "Disconnecting client.");
                    sender.TermClient();
                }
                else
                {
                    Logger.MajorDebug("Found implementor " + CC.DeclaringType.FullName + ", instantiating...");
                    AHostCommand o = (AHostCommand)Activator.CreateInstance(CC.DeclaringType);
                    o = (AHostCommand)Activator.CreateInstance(CC.DeclaringType);

                    Message.MessageResponse retMsg;
                    Message.MessageResponse retMsgAfterIO;

                    try
                    {
                        string trailingChars = "";
                        if (ExpectTrailers)
                        {
                            trailingChars = msg.GetTrailers();
                        }

                        if ((CheckLMKParity == false) || (Cryptography.LMK.LMKStorage.CheckLMKStorage()))
                        {
                            //Logger.MinorInfo("=== [" + commandCode + "], starts " + Utility.getTimeMMHHSSmmmm + " =======");

                            Logger.MajorDebug("Calling AcceptMessage()...");
                            o.AcceptMessage(msg);

                            Logger.MinorVerbose(o.DumpFields());
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            catch (Exception ex)
            {
            }
        }
Пример #17
0
        /// <summary>
        /// Handle a massage got from the client, and respone appropriately
        /// </summary>
        /// <param name="client"> the client</param>

        public void HandleClient(TcpClient client)
        {
            new Task(() =>
            {
                // m_logging.Log("Got new connection! ClientId: " + (++clientsId), MessageTypeEnum.INFO);
                bool connectionIsOn          = true; //Right now connection will be always on, but Maybe in future we will change it
                NetworkStream stream         = client.GetStream();
                BinaryReader reader          = new BinaryReader(stream);
                BinaryWriter writer          = new BinaryWriter(stream);
                ClientInformation clientInfo = new ClientInformation(stream, reader, writer, client);
                clientInfo.id = clientsId;
                m_allClients.Add(clientInfo);

                try
                {
                    while (connectionIsOn)
                    {
                        //Read command from client and Derserialize it
                        TCPEventArgs e = JsonConvert.DeserializeObject <TCPEventArgs>(reader.ReadString());
                        // m_logging.Log("Got Massage!!!: " + e.CommandID + " " + e.Args, MessageTypeEnum.INFO);
                        TCPEventArgs toSend;
                        string[] args = { e.Args };

                        bool success;
                        string result = m_controller.ExecuteCommand(e.CommandID, args, out success);
                        if (!success)
                        {
                            toSend = new TCPEventArgs((int)CommandEnum.ErrorOccurred, null);
                        }
                        else
                        {
                            toSend = new TCPEventArgs(e.CommandID, result);
                        }

                        //    m_logging.Log("Send: " + toSend.Args, MessageTypeEnum.INFO);

                        //Serialize the command to send, and send it
                        string serialized = JsonConvert.SerializeObject(toSend);
                        if (e.CommandID == (int)CommandEnum.CloseCommand)
                        {
                            if (success)
                            {
                                broadcastAllClients(serialized);
                                continue;
                            }
                        }
                        //If write won't success, we catch the execption, and then we close the client and remove it.
                        m_mutex.WaitOne();
                        writer.Write(serialized);
                        m_mutex.ReleaseMutex();
                        // m_logging.Log("Sent to client: " + toSend.Args, MessageTypeEnum.INFO);
                    }
                }

                catch (Exception)
                {
                    connectionIsOn = false;
                }
                m_allClients.Remove(clientInfo);
                client.Close();
                string logMassege = "Client " + clientInfo.id + " Disconnected";
                //m_logging.Log(logMassege, MessageTypeEnum.WARNING);
            }).Start();
        }
Пример #18
0
 private void listener_BeginConnect(object sender, TCPEventArgs e)
 {
     Console.WriteLine("A new Telnet Client accepted on slot {0} IP: {1}", e.SocketID, e.Endpoint.ToString());
     listener.WriteLine(e.SocketID, "Welcome to WowwoW Telnet Server...\r\nThis is a clear text Telnet server\t** Use at your own risk **\r\nSend <USER> <PASS> for authentication");
 }
Пример #19
0
 private void listener_BeginDisconnect(object sender, TCPEventArgs e)
 {
     Console.WriteLine("The Telnet client on slot {0} has disconnected", e.SocketID);
 }
Пример #20
0
        private void listener_BeginRead(object sender, TCPEventArgs e)
        {
            try
            {
                TCPClient client = ((TCPListener)sender).TCPClients[e.SocketID];

                string data         = GetData(e.Data);
                string commandValue = string.Empty;

                //Check for quit
                if (data.ToUpper() == "QUIT")
                {
                    Console.WriteLine("Goodbye");
                    client.DisconnectSocket();
                    return;
                }

                //Process the command
                if (!client.Authenticated)
                {
                    client.LoginAttempt++;

                    string[] vals = data.Split(' ');
                    if (vals == null || vals.Length < 2)
                    {
                        client.WriteLine("Send <USER> <PASS> for authentication");
                    }
                    else
                    {
                        Account acc = Konsole.Commands.HelperTools.GetAccByName(vals[0]);

                        if (acc != null && acc.Password.ToUpper() == vals[1].ToUpper())
                        {
                            if (acc.AccessLevel >= TelnetConfig.MinimumAccessLevel)
                            {
                                client.Authenticated = true;
                                client.Account       = acc;
                                client.WriteLine(string.Concat("Welcome ", acc.Username, ", you have been authenticated"));
                                Console.WriteLine("Telnet client authenticated: {0}", acc.Username);
                            }
                            else
                            {
                                client.WriteLine("Your access level is too low to use the telnet interface");
                                Console.WriteLine("Inadequite accesslevel on slot: {0} Account: {1} IP:{2}", e.SocketID, acc.Username, e.Endpoint.ToString());
                                client.DisconnectSocket();
                                return;
                            }
                        }
                        else
                        {
                            if (client.LoginAttempt == 3)
                            {
                                client.WriteLine("Login attempts exceeded. 3 strikes, you're out!");
                                client.DisconnectSocket();
                                Console.WriteLine("Telnet authentication attempts exceeded on IP: {0}", e.Endpoint.ToString());
                                return;
                            }
                            else
                            {
                                client.WriteLine("Bad credentials, try again\r\nSend <USER> <PASS> for authentication");
                            }
                        }
                    }
                }
                else
                {
                    KonsoleCommands.ProcessKonsoleInput(data);
                    Console.WriteLine("[WowwoW <? for help>]");
                }
            }
            catch (Exception ex)
            {
                SocketHelper.ShowError(this, ex);
            }
        }
Пример #21
0
 private void _tcpServer_MessageReceived(object sender, TCPEventArgs e)
 {
     //Logger.Log("message received", Severity.Info);
 }