Exemple #1
0
        /// <summary>
        /// Disconnect the client. Reserved for the server
        /// </summary>
        /// <param name="reason">Send the reason for disconnecting the client.</param>
        public void Disconnect(string reason)
        {
            var pair = new CommandParameterPair("DISCONN", Uri.EscapeDataString(reason));

            Client.SendCommand(pair);
            Client.CloseConnection();
        }
Exemple #2
0
        /// <summary>
        /// Send a shutdown message. Reserved for the server
        /// </summary>
        /// <param name="send">The message to send</param>
        public void SendShutdown(string send)
        {
            var pair = new CommandParameterPair("SDOWN", Uri.EscapeDataString(send), "0");

            Client.SendCommand(pair);
            Client.CloseConnection();
        }
        public static void ManageAnonymous(object socket)
        {
            AnonymousThread client = (AnonymousThread)socket;

            try
            {
                var clientStream = client.Client.GetStream();
                if (Program.ServerState == 0)
                {
                    SocketUtilities.SendShutdown(clientStream, "The server is shutting down", "0");
                    clientStream.Close();
                    return;
                }
                string smessage = SocketUtilities.RecieveMessage(clientStream, SocketUtilities.RecieveMessageLength(clientStream));
                if (smessage == null)
                {
                    Program.Disconnect(ThreadType.AnonymousThread, client.Guid);
                    return;
                }
                CommandParameterPair message = MessageUtilites.DecodeMessage(smessage);
                var builder = new StringBuilder();
                foreach (string i in message.Parameters)
                {
                    builder.Append(String.Format("{0} with", i));
                }
                ConsoleUtilities.PrintCommand(String.Format("{0} has sent command {1} with parameters {2}", client.Guid, message.Command, builder));
                InitializeCommand execute;
                if (Program.InitializeCommands.TryGetValue(message.Command, out execute))
                {
                    execute(client.Client, message.Parameters);
                }
                else
                {
                    SocketUtilities.SendError(clientStream, "Unable to find command (Concurrency Issues)");
                    clientStream.Close();
                }
            }
            catch (SocketException e)
            {
                if (client.Client.Client.RemoteEndPoint == null)
                {
                    Console.WriteLine("A severe error has occurred with the clientStream. Data: {0}", e.Data);
                    return;
                }
                Console.WriteLine("Error: A clientStream has disconnected from {0}. ", (client.Client.Client.RemoteEndPoint as IPEndPoint).Address);
            }
            catch (IOException e)
            {
                if (client.Client.Client.RemoteEndPoint == null)
                {
                    Console.WriteLine("A severe error has occurred with the clientStream. Data: {0}", e.Data);
                    return;
                }
                Console.WriteLine("Error: A clientStream has disconnected from {0}. ", (client.Client.Client.RemoteEndPoint as IPEndPoint).Address);
            }
        }
        public static string EncodeMessage(CommandParameterPair message)
        {
            if (message.ParameterLength == 0)
            {
                return(message.Command);
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(String.Format("{0} ", message.Command));
            foreach (string parameter in message.Parameters)
            {
                builder.Append(String.Format("{0}&", Uri.EscapeDataString(parameter)));
            }
            return(builder.ToString().Substring(0, builder.Length - 1));
        }
Exemple #5
0
 /// <summary>
 /// Reserved for the server
 /// </summary>
 /// <param name="command">The command to be sent</param>
 public void SendCommand(CommandParameterPair command)
 {
     Client.SendCommand(command);
 }
Exemple #6
0
        public void Abort(string reason)
        {
            var pair = new CommandParameterPair("DISCONN", Uri.EscapeDataString(reason));

            Client.Abort();
        }
Exemple #7
0
        /// <summary>
        /// Send a message to the client.
        /// </summary>
        /// <param name="username">The user sending the message</param>
        /// <param name="message">The message to send</param>
        public void SendMessage(string username, string message)
        {
            var pair = new CommandParameterPair("NEWMSG", Uri.EscapeDataString(username), Uri.EscapeDataString(message));

            Client.SendCommand(pair);
        }
Exemple #8
0
        private static void Main(string[] args)
        {
            //Initialize the server
            InitializeServer.Start();

            Console.WriteLine("Server is starting");
            foreach (Thread thread in AcceptThreads)
            {
                thread.Start();
            }
            Console.WriteLine("Server has been started");
            ConsoleUtilities.PrintInformation("Go to http://messaging.explodingbytes.com/console/keys for more information on what to do.");
            ConsoleUtilities.PrintInformation("Press 'q' to stop the server.");
            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key == new ConsoleKeyInfo('q', ConsoleKey.Q, false, false, false))
                {
                    ServerState = 0;
                    ConsoleUtilities.PrintInformation("Server is stopping");
                    ServerSocket.Stop();
                    break;
                }
                if (key == new ConsoleKeyInfo('u', ConsoleKey.U, false, false, false))
                {
                    ServerState = 2;
                    byte[] bytes = Encoding.UTF8.GetBytes("INFOREQ");
                    for (int i = 0; i < 2; i++)
                    {
                        Socket sendSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                        sendSocket.Connect(IPAddress.Loopback, 2015);
                        sendSocket.SendTo(BitConverter.GetBytes(bytes.Length), 0, 4, SocketFlags.None,
                                          new IPEndPoint(IPAddress.Loopback, 2015));
                        sendSocket.SendTo(bytes, 0, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 2015));
                        sendSocket.Close();
                    }
                    Thread.Sleep(1000);
                    Console.WriteLine("Users:");
                    foreach (IMessagingClient client in Clients.Values)
                    {
                        Console.WriteLine("Username: {0, 15} | Type: {1, 15} | IsOnline: {2, 15}", client.UserName, client.Client.ClientType, client.IsAfk);
                    }
                    ServerThread.ResumeThreads();
                }
                if (key == new ConsoleKeyInfo('c', ConsoleKey.C, false, false, false))
                {
                    ServerState = 2;
                    byte[] bytes = Encoding.UTF8.GetBytes("INFOREQ");
                    for (int i = 0; i < 2; i++)
                    {
                        Socket sendSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                        sendSocket.Connect(IPAddress.Loopback, 2015);
                        sendSocket.SendTo(BitConverter.GetBytes(bytes.Length), 0, 4, SocketFlags.None,
                                          new IPEndPoint(IPAddress.Loopback, 2015));
                        sendSocket.SendTo(bytes, 0, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 2015));
                        sendSocket.Close();
                    }
                    Thread.Sleep(1000);
                    string command    = Console.ReadLine();
                    var    parameters = new List <string>();
                    while (true)
                    {
                        string var = Console.ReadLine();
                        if (String.IsNullOrEmpty(var))
                        {
                            break;
                        }
                        parameters.Add(var);
                    }
                    var pair = new CommandParameterPair(command, parameters.ToArray());
                    foreach (IMessagingClient client in Clients.Values)
                    {
                        client.SendCommand(pair);
                    }
                    ServerThread.ResumeThreads();
                }
            }

            foreach (IMessagingClient service in Clients.Values)
            {
                service.SendShutdown("The server is shutting down");
            }

            foreach (IMessagingClient service in Clients.Values)
            {
                service.Abort("The server is shutting down.");
            }
            Thread.Sleep(10000);
            Console.WriteLine("You may exit safely at this point by ending the process");
            // Clean up code
            foreach (KeyValuePair <string, Thread> thread in ClientThreads)
            {
                thread.Value.Abort();
                thread.Value.Join();
            }
            foreach (KeyValuePair <string, Thread> thread in AnonymousThreads)
            {
                thread.Value.Abort();
                thread.Value.Join();
            }
            Console.WriteLine("Server has stopped. Press any key to exit");
            Console.ReadKey();
            Environment.Exit(0);
        }
        public static void AcceptNewClients()
        {
            Console.WriteLine("Thread started");
            while (true)
            {
                try
                {
                    TcpClient tcpClient = Program.ServerSocket.AcceptTcpClient();
                    if (Program.ServerState == 0)
                    {
                        ConsoleUtilities.PrintCritical("Thread has been ended {0}", DateTime.UtcNow);
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    NetworkStream clientStream = tcpClient.GetStream();
                    ConsoleUtilities.PrintCommand("Connection has been accepted from {0}", tcpClient.Client.RemoteEndPoint);

                    if (Program.AnonymousThreads.ContainsKey(tcpClient.Client.RemoteEndPoint.ToString()))
                    {
                        SocketUtilities.SendInvalid(clientStream, "Your network is already connected. Try again later.");
                        tcpClient.Close();
                        continue;
                    }

                    int messageLength = SocketUtilities.RecieveMessageLength(clientStream);
                    if (messageLength == -1)
                    {
                        ConsoleUtilities.PrintCommand("Connection has been closed for {0}", tcpClient.Client.RemoteEndPoint);
                        tcpClient.Close();
                        continue;
                    }
                    string stringmessage = SocketUtilities.RecieveMessage(clientStream, messageLength);
                    if (stringmessage == null)
                    {
                        tcpClient.Close();
                        continue;
                    }

                    CommandParameterPair message = MessageUtilites.DecodeMessage(stringmessage);
                    if (message == null)
                    {
                        SocketUtilities.SendInvalid(clientStream, "The message was formatted incorrectly.");
                        tcpClient.Close();
                        continue;
                    }

                    if (!Program.InitializeCommands.ContainsKey(message.Command))
                    {
                        SocketUtilities.SendInvalid(clientStream, "The command was not found");
                        tcpClient.Close();
                        continue;
                    }

                    InitializeCommand execute;
                    if (Program.InitializeCommands.TryGetValue(message.Command, out execute))
                    {
                        execute(tcpClient, message.Parameters);
                        continue;
                    }
                    SocketUtilities.SendError(clientStream, "Unable to find command (Concurrency Issues)");
                    if (Program.ServerState == 0)
                    {
                        Console.WriteLine("Thread has been ended");
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                }
                catch (ThreadAbortException e)
                {
                    Console.WriteLine("Thread has been stopped {0}", e.Data.Values);
                    return;
                }
                catch (InvalidOperationException e)
                {
                    ConsoleUtilities.PrintCritical("Accept thread has been terminated {0}", e.Message);
                    return;
                }
                catch (ThreadInterruptedException)
                {
                    Console.WriteLine("Resuming accepting threads");
                }
                catch (IOException e)
                {
                    ConsoleUtilities.PrintWarning("Impropert disconnect. {1}", e.Message);
                }
                catch (SocketException e)
                {
                    ConsoleUtilities.PrintWarning("Improper disconnect. Data: {0}", e.Data);
                }
            }
        }
        public static void ManageClient(object service)
        {
            IMessagingClient client = (IMessagingClient)service;

            while (true)
            {
                try
                {
                    if (Program.ServerState == 0)
                    {
                        client.SendShutdown("The server is shutting down.");
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    CommandParameterPair message = client.RecieveMessage();
                    if (message == null)
                    {
                        Program.Disconnect(ThreadType.ClientThread, client.UserName);
                        return;
                    }
                    var parameters = new StringBuilder();
                    foreach (string param in message.Parameters)
                    {
                        parameters.Append(param + " ");
                    }
                    ConsoleUtilities.PrintCommand("Command {0} was sent from the user {1} with parameters '{2}'", message.Command,
                                                  client.UserName,
                                                  parameters);
                    ClientCommand command;
                    if (Program.ClientCommands.TryGetValue(message.Command, out command))
                    {
                        CommandParameterPair classic = command(client.UserName, message.Parameters);
                        if (classic == null)
                        {
                            continue;
                        }
                        client.SendCommand(classic);
                    }
                    else
                    {
                        client.SendInvalid(String.Format("Unknown command: {0}", message.Command));
                    }
                    if (Program.ServerState == 0)
                    {
                        client.SendShutdown("The server is shutting down.");
                        return;
                    }
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (ThreadInterruptedException)
                {
                }
                catch (ObjectDisposedException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (IOException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (SocketException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (NetworkInformationException e)
                {
                    ConsoleUtilities.PrintWarning("A user has disconnected {0}", e.Message);
                    client.Disconnect("An unknown error has occurred.");
                    Program.Disconnect(ThreadType.ClientThread, client.Client.UserName);
                    return;
                }
            }
        }
 public static void SendCommand(NetworkStream clientStream, CommandParameterPair pair)
 {
     byte[] message = Encoding.UTF8.GetBytes(MessageUtilites.EncodeMessage(pair));
     clientStream.Write(BitConverter.GetBytes(message.Length), 0, 4);
     clientStream.Write(message, 0, message.Length);
 }