Exemplo n.º 1
0
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8001);
            TcpClient   clientSocket = default(TcpClient);
            int         counter      = 0;
            GameDealer  gamed        = new GameDealer();

            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started");
            Console.WriteLine(" >> " + "Server IP: " + GetLocalIP());
            Console.WriteLine(" >> " + "Waiting for 2 Clients...");
            counter = 0;
            while (true)
            {
                counter++;
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                HandleClient client = new HandleClient();
                client.startClient(clientSocket, Convert.ToString(counter), gamed);
                if (counter == 2)
                {
                    Console.WriteLine("2 Clients has connected to the server.");
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
        private void InitSocket()
        {
            log.logView        += "Server1 Start...\n";
            server              = new TcpListener(IPAddress.Any, 9991);
            this.stopMachinery += server.Stop;
            clientSocket        = default(TcpClient);
            server.Start();
            log.logView += "Server1 opened successfully\n";

            while (true)
            {
                try
                {
                    log.logView += "Server1 is waiting for clients...\n";
                    clientSocket = server.AcceptTcpClient(); // client 소켓 접속 허용


                    NetworkStream stream = clientSocket.GetStream();

                    byte[] buffer    = new byte[1024]; // 버퍼
                    int    bytes     = stream.Read(buffer, 0, buffer.Length);
                    string user_name = Encoding.Unicode.GetString(buffer, 0, bytes);
                    user_name = user_name.Substring(0, user_name.IndexOf("$")); // client 사용자 명

                    clientList.Add(clientSocket, user_name);                    // cleint 리스트에 추가
                    log.logView += (user_name + " is accepted.\n");

                    HandleClient h_client = new HandleClient(); // 클라이언트 추가
                    h_client.OnReceived      += new HandleClient.MessageDisplayHandler(OnReceived);
                    h_client.OnDisconnected  += new HandleClient.DisconnectedHandler(h_client_OnDisconnected);
                    h_client.OnSent          += new HandleClient.SendJsonHandler(OnSent);
                    h_client.OnSentLoginInfo += new HandleClient.SendLoginJsonHandler(OnSentLoginInfo);
                    h_client.startClient(clientSocket, clientList);
                }
                catch (SocketException se)
                {
                    break;
                }catch (Exception ex)
                {
                    break;
                }
            }

            if (clientSocket != null)
            {
                clientSocket.Close(); // client 소켓 닫기
            }


            log.logView += "Server1 closed\n";
        }
Exemplo n.º 3
0
            private void runServer()
            {
                while (true)
                {
                    try {
                        serverSocket = new TcpListener(IPAddress.Any, port);
                        TcpClient clientSocket = default(TcpClient);
                        int       counter      = 0;

                        try {
                            serverSocket.Start();
                            running = true;
                        }
                        catch {
                            running = false;
                            return;
                        }

                        counter = 0;
                        while (running)
                        {
                            try {
                                counter     += 1;
                                clientSocket = serverSocket.AcceptTcpClient();
                                //Logging.log("Client No:" + Convert.ToString(counter) + " started!", LogPrior.Importand);
                                HandleClient client = new HandleClient();
                                this.clients.Add(client);
                                client.startClient(this, clientSocket, Convert.ToString(counter));
                            }
                            catch { }
                        }
                        if (clientSocket != null)
                        {
                            clientSocket.Close();
                        }
                        if (serverSocket != null)
                        {
                            serverSocket.Stop();
                        }
                    }
                    catch (Exception ex) {
                        Logging.logException(string.Format("Cannot open server on port {0}", port), ex);
                    }
                }
            }
Exemplo n.º 4
0
        private void startServer()
        {
            IPAddress ipAd = IPAddress.Parse(this.compIPAddress.Text);
            try
            {
                // use local m/c IP address, and 
                // use the same in the client

                /* Initializes the Listener */
                tcpListener = new TcpListener(ipAd, Convert.ToInt32(this.portNumber.Text));

                /* Start Listeneting at the specified port */
                tcpListener.Start();
            }
            catch (SocketException soEx)
            {
                MessageBox.Show("Error...\n Socket: " + this.portNumber.Text + " of IP address: " + ipAd +
                    " could not be opened.");
                Console.Write("Error..... " + soEx.StackTrace);
                tcpListener.Stop();
                tcpListener = null;
                updateGUI(true);
                return;
            }
            int clientCounter = 0;
            try
            {
                AppendToTextBox("Ready....." + "\n");
                while (this.continueListening && serverThread.IsAlive)
                {
                    //if (NaoConnected) // Comment this line for debugging purposes
                    {
                        clientCounter = clientCounter + 1;
                        TcpClient clientSocket = tcpListener.AcceptTcpClient();
                        HandleClient client = new HandleClient();
                        client.startClient(clientSocket, this, clientCounter);
                    }
                }

                tcpListener.Stop();

            }
            catch (Exception ex)
            {
                Console.Write("Error..... " + ex.StackTrace);
            }
        }
Exemplo n.º 5
0
        private void serverThread()
        {
#if DEBUG
            TcpListener serverSocket = new TcpListener(6969);
#else
            TcpListener serverSocket = new TcpListener(6969);
#endif
            TcpClient clientSocket = default(TcpClient); //ClientSocket
            serverSocket.Start();
            Console.Write(" >> " + "Server Started");

            int counter = 0;
            while (true)
            {
                try
                {
                    counter     += 1;
                    clientSocket = serverSocket.AcceptTcpClient();

                    string IPAddress = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString();

                    Console.WriteLine("IPAddress: " + IPAddress);

                    if (IPAddress != "127.0.0.1" && IPAddress != "109.199.125.101")
                    {
                        bool     found    = false;
                        AntiSpam antispam = new AntiSpam();
                        foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections))
                        {
                            if (cachedconnection.IP == IPAddress)
                            {
                                found = true;

                                antispam = cachedconnection;
                            }
                        }

                        if (found)
                        {
                            Console.WriteLine("IP Found -> " + antispam.Attempts + " IP= " + antispam.IP);

                            if (antispam.Attempts > ConnectionsMax)
                            {
                                //Check if it exceeds double the connections max
                                if (antispam.Attempts == (ConnectionsMax * 2))
                                {
                                    Console.WriteLine("Blocking IP");

                                    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                                    INetFwRule    firewallRule   = firewallPolicy.Rules.OfType <INetFwRule>().Where(x => x.Name == "Blocked: " + IPAddress).FirstOrDefault();

                                    if (firewallRule == null)
                                    {
                                        firewallRule                 = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                                        firewallRule.Name            = "Blocked: " + IPAddress;
                                        firewallRule.Description     = "Blocking Traffic";
                                        firewallRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                                        firewallRule.LocalPorts      = "6969";
                                        firewallRule.RemoteAddresses = IPAddress;
                                        firewallRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                                        firewallRule.Enabled         = true;
                                        firewallRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                                        firewallPolicy.Rules.Add(firewallRule);
                                    }

                                    Log.WriteLine("Blocked IP (Connection Quota) [" + IPAddress + "]", "Blocked");
                                }

                                foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections))
                                {
                                    if (cachedconnection.IP == antispam.IP)
                                    {
                                        cachedconnection.Attempts  = cachedconnection.Attempts + 1;
                                        cachedconnection.Attempted = DateTime.Now;
                                    }
                                }

                                Console.WriteLine("Blocked Connection {0} Times -> " + IPAddress, antispam.Attempts);

                                clientSocket.NoDelay = true;

                                NetworkStream networkStream = clientSocket.GetStream();

                                //Byte Streams
                                byte[] outStream = Encoding.ASCII.GetBytes("Connection Quota Reached");

                                byte[] outSize = BitConverter.GetBytes(outStream.Length);

                                //Network Streams
                                networkStream.Write(outSize, 0, outSize.Length);
                                networkStream.Write(outStream, 0, outStream.Length);
                                networkStream.Flush();

                                Console.Write(">> Size=" + BitConverter.ToInt32(outSize, 0) + " Response: Connection Quota Reached");

                                clientSocket.Close();

                                continue;
                            }
                            else
                            {
                                foreach (AntiSpam cachedconnection in new List <AntiSpam>(Connections))
                                {
                                    if (cachedconnection.IP == antispam.IP)
                                    {
                                        cachedconnection.Attempts  = cachedconnection.Attempts + 1;
                                        cachedconnection.Attempted = DateTime.Now;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("IP Not Found (Adding IP) -> IP= " + IPAddress);

                            Connections.Add(new AntiSpam(IPAddress, 1, DateTime.Now));
                        }
                    }

                    clientSocket.NoDelay = true;

                    clientSocket.ReceiveTimeout = (60000 * 5);

                    Console.Write(" >> " + "Client No:" + Convert.ToString(counter) + " started!");

                    Connection   connection = new Connection(counter, clientSocket);
                    HandleClient client     = new HandleClient();
                    client.startClient(connection);

                    lock (TcpClients)
                    {
                        TcpClients.Add(connection);
                    }

                    Log.WriteLine("Client Connected [" + IPAddress + "]", "Connections");
                }
                catch (Exception ex)
                {
                    Log.WriteLine("Client Connection Failed", "DEBUG");
                    Log.WriteLine(ex.ToString(), "DEBUG");
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.Write(" >> " + "exit");
            Console.ReadLine();
        }