예제 #1
0
        public void Start()
        {
            IPEndPoint my_ip = new IPEndPoint(Tools.GetMyIP(), PORT);

            Socket nw_obj = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                nw_obj.Bind(my_ip);

                nw_obj.Listen(MAX_REQUEST_COUNT);

                log.WriteLog("Сервер запущен. Ожидание подключений.");

                ThreadPool.SetMaxThreads(MAX_REQUEST_COUNT, MAX_REQUEST_COUNT);
                while (true)
                {
                    Socket client_connection = nw_obj.Accept();

                    //Может быть косяк
                    log.WriteLog(Tools.GetIPFromSocket(client_connection) + " - Подключен");

                    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
                    {
                        ClientHandler client = new ClientHandler(client_connection, db, log, connections);
                        client.Start();
                    }));
                }
            }
            catch (Exception ex) { /*дописать*/ MessageBox.Show(ex.Message); }
        }
예제 #2
0
        private static void AcceptConnections()
        {
            Console.WriteLine("Accepting connections");
            Console.WriteLine("");

            while (IsRunning)
            {
                TcpClient IncomingClient;
                try
                {
                    IncomingClient = listener.AcceptTcpClient();
                    ClientHandler handler = new ClientHandler(IncomingClient);
                    handler.ClientHandlerStop += Handler_ClientHandlerStop;
                    handler.ID = count;
                    count++;
                    handler.Start();
                    Handlers.Add(handler);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.Interrupted)
                    {
                        Console.WriteLine("Quitting...");
                    }
                    else
                    {
                        Console.WriteLine("Error occured: " + e.ToString());
                    }
                }
            }

            foreach (ClientHandler ch in Handlers)
            {
                ch.Stop();
            }
        }
예제 #3
0
        private static void Main(string[] args)
        {
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            TcpListener server       = null;
            TcpClient   clientSocket = null;

            try
            {
                //read from the file
                X509Certificate2 serverCertificate = new X509Certificate2(_serverCertificateFile, _serverCertificatePassword);
                // Set the TcpListener on port 43594 at localhost.
                int       port      = 43594;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                server = new TcpListener(localAddr, port);
                //Creates a socket for client communication
                clientSocket = default;
                // Start listening for client requests.
                server.Start();
                Console.WriteLine("TcpListener Started.");

                /*
                 * Read All chatrooms that are serialized or in database here and add them to the list
                 */
                Room globalChat = new Room("Daniel", "Global", true);
                Rooms.Add("Global", globalChat);

                /*
                 * Enter the listening loop. This will accept a TCP client and then attempt to authenticate the user.
                 * If the user is authenticated, a thread will be created to handle the client communication of the user,
                 * while the loop continues listening for new client connections.
                 */
                while (true)
                {
                    clientSocket = server.AcceptTcpClient();
                    string clientIP = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString();
                    Console.WriteLine("Incoming client connection from: " + clientIP);
                    SslStream sslStream = new SslStream(clientSocket.GetStream(), false, App_CertificateValidation);
                    Console.WriteLine("Accepted client " + clientSocket.Client.RemoteEndPoint.ToString());

                    sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls12, false);
                    Console.WriteLine("SSL authentication completed.");

                    // Read the username and password of incoming connection.
                    BinaryReader reader      = new BinaryReader(sslStream);
                    string       userName    = reader.ReadString();
                    string       password    = reader.ReadString();
                    string       chatRoom    = reader.ReadString();
                    bool         authResult  = false;
                    string       authMessage = string.Empty;
                    //create folder if it doesn't exist
                    Directory.CreateDirectory("./Users");
                    User user = new User();
                    if (File.Exists("./Users/" + userName + ".xml")) //load user info if user exists
                    {
                        user = DeSerializeObject <User>("./Users/" + userName + ".xml");
                    }
                    else //if user does not exist, create one
                    {
                        user.Username = userName;
                        string saltedHashPassword = GenerateKeyHash(password);
                        user.Password = saltedHashPassword;
                        SerializeObject <User>(user, "./Users/" + userName + ".xml");
                    }

                    if (!ComparePasswords(user.Password, password))
                    {
                        authResult  = false;
                        authMessage = "Your password or username is incorrect.";
                    }
                    else if (Rooms.TryGetValue(chatRoom, out Room r))
                    {
                        if (r.IsUsedLoggedIn(userName))
                        {
                            authResult  = false;
                            authMessage = "You are already logged in.";
                        }
                        else
                        {
                            authResult = true;
                        }
                    }
                    else
                    {
                        authResult = true;
                    }
                    // send the authentication results back to the client if it failed
                    if (!authResult)
                    {
                        BinaryWriter writer = new BinaryWriter(sslStream);
                        writer.Write(authResult);
                        writer.Write(authMessage);
                        writer.Close();
                        sslStream.Close();
                    }
                    else
                    {
                        BinaryWriter writer = new BinaryWriter(sslStream);
                        writer.Write(authResult);
                        writer.Write(authMessage);
                        Console.WriteLine(user.Username + " has connected from: " + clientIP);
                        user.PublicKey = reader.ReadString();
                        ClientHandler client = new ClientHandler(sslStream, user);
                        client.Start();
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
                clientSocket.Close();
            }

            // Placed this read input to stop it from closing immedietely due to exceptions, so we can see what the issue is.
            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }