Exemplo n.º 1
0
        public void ProcessIncomingConnection( )
        {
            while (true)
            {
                try
                {
                    TcpClient client = Listener.AcceptTcpClient( );
                    client.GetStream( );

                    SslStream stream = new SslStream(
                        client.GetStream( ),
                        false);

                    stream.AuthenticateAsServer(ServerCertificate,
                                                false,
                                                SslProtocols.Tls,
                                                true);

                    Clients.Add(new StreamManager(stream));
                }
                catch (ThreadAbortException)
                {
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Returns the Packet of data sent by a TcpClient
        /// </summary>
        /// <param name="serverData">Returns the ServerData object if the packet was a ServerDataPacket</param>
        /// <returns>The Packet sent</returns>
        IDataPacket ListenForPackets(out Data data)
        {
            Logger.Instance.Log("Waiting for a connection");
            var client = Listener.AcceptTcpClient();

            Logger.Instance.Log("Connected");
            byte[]      bytes  = new byte[Packet.MAX_BYTE_LENGTH];
            IDataPacket packet = null;

            if (client.GetStream().Read(bytes, 0, bytes.Length) != 0)
            {
                packet = Packet.ToPacket(bytes);
            }

            data = new Data {
                TcpClient = client
            };

            if (packet is ServerDataPacket)
            {
                var sPacket = (ServerDataPacket)packet;
                data = new Data(ConnectedClients.Count == 0 ? 0 : ConnectedClients.Last().ID + 1)
                {
                    TcpClient = client, IPv4 = sPacket.IPv4, Name = sPacket.Name, Port = sPacket.Port
                };
                ConnectedClients.Add(data);
                Logger.Instance.Log($"Server @ {data.IPv4} added to collection");
            }

            return(packet);
        }
Exemplo n.º 3
0
        public async void Start()
        {
            await Task.Run(() => {
                Listener.Start();
                while (true)
                {
                    _main.WriteConsole("In attesa di connessione...");


                    //qui il listener inizia ad ascoltare, il metodo Accept è bloccante e attende l'arrivo di una richiesta di connessione tcp
                    //e accettandola crea un oggetto tcp client
                    TcpClient client = Listener.AcceptTcpClient();


                    string tmp = "client" + (ClientConnessi.Count + 1);

                    //qui invece facco partire un metodo in async che ascolta sul singolo client
                    ListenToTheStereo(client);

                    //aggiungo il client alla lista di client connessi
                    ClientConnessi.Add(tmp, client);

                    //aggiorno l'elenco sulla finestra
                    _main.AggiornaClientView();
                    //scrivo un aggiornamento in modo testuale
                    _main.WriteConsole("nuova connessione con: " + client.Client.LocalEndPoint.ToString());
                }
            });
        }
Exemplo n.º 4
0
 private async Task Listen()
 {
     try
     {
         Task CheckerTask = Task.CompletedTask;
         while (!CancellationToken.IsCancellationRequested)
         {
             if (Clients.Count <= Configuration.MaximumNumberOfConnections && Listener.Pending())
             {
                 var client = Listener.AcceptTcpClient();
                 var t      = new T();
                 t.Init(client, this);
                 Clients.Add(t);
                 this.OnClientConnected(t);
             }
             else
             {
                 if (CheckerTask.IsCompleted)
                 {
                     CheckerTask = Task.Run(() => CheckClients());
                 }
                 await Task.Delay(10, CancellationToken.Token);
             }
         }
     }
     catch (Exception ex)
     {
         OnError(ex);
     }
 }
Exemplo n.º 5
0
        void AcceptClients()
        {
            int Id = 0;

            while (true)
            {
                try
                {
                    TcpClient   CurrentClient = Listener.AcceptTcpClient();
                    ClassToSend MSG           = (ClassToSend)bf.Deserialize(CurrentClient.GetStream());
                    ClassToSend msg           = new ClassToSend();
                    msg.Id = Id;
                    Users.Add(new ServerUser(Id++, MSG.Name, CurrentClient));
                    msg.Users = Users;
                    msg.Type  = Type.LobbyUpdate;
                    foreach (var user in Users)
                    {
                        SendMessage(user, msg);
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                }
            }
        }
Exemplo n.º 6
0
        public void AcceptClients(Action <object> callbackForReceiveData)
        {
            CallbackForReceiveData = callbackForReceiveData;
            IsOpen = true;
            Listener.Start();

            ProcessClientsTasks.Add(Task.Run(() =>
            {
                try
                {
                    while (IsOpen)
                    {
                        var client = Listener.AcceptTcpClient();
                        Clients.Add(client);
                    }
                }
                catch (System.Net.Sockets.SocketException ex)
                {
                }
            }));

            ProcessClientsTasks.Add(Task.Run(() =>
            {
                while (IsOpen)
                {
                    if (Clients.Count > 0)
                    {
                        Receive();
                    }
                }
            }));
        }
Exemplo n.º 7
0
        public void FindClients()
        {
            int[]  curClientsId = new int[5];
            byte[] data         = new byte[Constants.SIZE_OF_BYTES_NULL];

            StartListener();
            while (CheckEveryoneIsFound(curClientsId) == false)
            {
                //Get connected
                Console.WriteLine("Waiting for a connection...");
                TcpClient     newClient = Listener.AcceptTcpClient();
                NetworkStream newStream = newClient.GetStream();
                Console.WriteLine("Connected");

                int newClientId = GetDataFromClient(0, newStream)[0];

                //Who and what?
                Tuple <int, int> correctIdRepeate = GetCorrectIdForClient_GetRepeate(newClientId);
                data[0] = Constants.ID_SERVER;
                data[1] = Convert.ToByte(correctIdRepeate.Item1);
                curClientsId[correctIdRepeate.Item1] = 1;
                Clients[correctIdRepeate.Item1]      = newClient;
                Streams[correctIdRepeate.Item1]      = newStream;

                //Send reply
                SendDataToCLient(data, 0, newStream);
            }
            Console.WriteLine("First connection is done.");
            Console.WriteLine("GameType: " + Constants.GAMETYPE_MESS[GameType]);
        }
Exemplo n.º 8
0
 public void AcceptConnections()
 {
     while (true)
     {
         Honeypots.Add(Listener.AcceptTcpClient());
         Console.WriteLine("Client " + IPAddress.Parse(((IPEndPoint)Honeypots.Last().Client.RemoteEndPoint).Address.ToString()) + " has connected!");
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Beginnt auf dem Port zu lauschen
        /// Wird nebenläufig ausgeführt
        /// </summary>
        private void Run()
        {
            // Client-Task
            var clientTask = Task.Factory.StartNew(() =>
            {
                while (!ClientTokenSource.IsCancellationRequested)
                {
                    TcpClient client = null;

                    lock (Queue)
                    {
                        client = Queue.Count > 0 ? Queue.Dequeue() : null;
                    }

                    if (client != null)
                    {
                        // Worker-Task
                        var workerTask = Task.Factory.StartNew(() =>
                        {
                            HandleClient(client);
                        });
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                }
            }, ClientTokenSource.Token);

            // Server-Task
            while (!ServerTokenSource.IsCancellationRequested)
            {
                if (Listener == null)
                {
                    break;
                }

                try
                {
                    var client = Listener.AcceptTcpClient();

                    lock (Queue)
                    {
                        if (Queue.Count < ConnectionLimit)
                        {
                            Queue.Enqueue(client);
                        }
                        else
                        {
                            client.Close();
                        }
                    }
                }
                catch
                {
                }
            }
        }
Exemplo n.º 10
0
 private void ClientListenLoop()
 {
     Listener.Start();
     while (true)
     {
         RemoteClient client = new RemoteClient(Listener.AcceptTcpClient());
         Clients.AddClient(client);
     }
 }
Exemplo n.º 11
0
 public void Update_Client()
 {
     if (IsClientConnected)
     {
         return;                          // Make sure no other client is already connected
     }
     Client = Listener.AcceptTcpClient(); // Accept the TCP request
     Stream = Client.GetStream();         // Get the network stream of the client
 }
Exemplo n.º 12
0
 /// <summary>
 /// Waits for connections any makes a new delegate for each client
 /// </summary>
 protected override void AcceptConnetion()
 {
     while (true)
     {
         TcpClient client = Listener.AcceptTcpClient();
         stream = client.GetStream();
         DataTransmissionDelegate transmissionDelegate = new DataTransmissionDelegate(BeginDataTransmission);
         transmissionDelegate.BeginInvoke(stream, TransmissionCallback, client);
     }
 }
Exemplo n.º 13
0
        Data AcceptClient()
        {
            Logger.Instance.Log("Waiting for a connection");
            var client = Listener.AcceptTcpClient();

            //Logger.Instance.Log("Server Connected");
            return(new Data {
                TcpClient = client
            });
        }
Exemplo n.º 14
0
 public void HandleListen()
 {
     acceptingTask = Task.Factory.StartNew(
         () => {
         while (true)
         {
             TcpClient client = Listener.AcceptTcpClient();
             mClientQueue.Enqueue(client);
         }
     }
         );
 }
Exemplo n.º 15
0
        protected override void AcceptClient()
        {
            while (true)
            {
                TcpClient tcpClient = Listener.AcceptTcpClient();

                Stream = tcpClient.GetStream();

                TransmissionDataDelegate transmissionDelegate = new TransmissionDataDelegate(BeginDataTransmission);
                transmissionDelegate.BeginInvoke(Stream, TransmissionCallback, tcpClient);
            }
        }
Exemplo n.º 16
0
 public void GetNewConnection()
 {
     while (true)
     {
         TcpClient     client  = Listener.AcceptTcpClient();
         ClientElement element = new ClientElement(client, this);
         Clients.Add(element);
         OnNewConnectionCreated(this, new ClientConnectedEventArgs()
         {
             ConnectedClient = client
         });
     }
 }
Exemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>Not Thread safe! draait niet in main thread</remarks>
        private void ListenForClients()
        {
            try
            {
                Listener.Start();
            }
            catch (Exception ex)
            {
                OnListenerError(new ListenerErrorEventArgs(ex));
            }
            while (Listening)
            {
                TcpClient CL = null;
                try
                {
                    CL = Listener.AcceptTcpClient();
                    if (Listening == false)
                    {
                        return;
                    }
                }
                catch (SocketException se)
                {
                    switch (se.SocketErrorCode)
                    {
                    case SocketError.Interrupted:
                        if (Listening == false)
                        {
                            return;
                        }

                        break;
                    }

                    OnListenerError(new ListenerErrorEventArgs(se));
                }
                catch (Exception ex)
                {
                    OnListenerError(new ListenerErrorEventArgs(ex));

                    Listening = false;
                }


                if (CL != null)
                {
                    OnClientConnected(new ClientConnectedEventArgs(CL));
                }
                CL = null;
            }
        }
Exemplo n.º 18
0
        private void ReceiveThreadFunction()
        {
            try
            {
                // Start listening for client requests.
                Listener.Start();

                // Buffer for reading data
                byte[] bytes = new byte[256];

                // Enter the listening loop.
                while (true)
                {
                    // Perform a blocking call to accept requests.
                    var client = Listener.AcceptTcpClient();

                    // Get a stream object for reading and writing
                    var stream = client.GetStream();

                    int count = stream.Read(bytes, 0, bytes.Length);
                    if (count != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        string data = Encoding.ASCII.GetString(bytes, 0, count);

                        var parts = data.Split(':');
                        switch (parts[0])
                        {
                        case "+":
                            Regist(parts[1], int.Parse(parts[2]));
                            break;

                        case "-":
                            Regist(parts[1], int.Parse(parts[2]));
                            break;
                        }
                    }

                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Host.Logger.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                Listener.Stop();
            }
        }
Exemplo n.º 19
0
        protected virtual void ListenOnNewClients()
        {
            Listener.Start();

            while (true)
            {
                TcpClient connectedClient = Listener.AcceptTcpClient();

                var client = HandleNewConnectedClient(connectedClient, connectedClient.GetStream());

                Clients.Add(client);
                OnClientConnected(new ClientConnectedEventArgs(client));
                Log.Info("New client connected (IP: " + connectedClient.Client.RemoteEndPoint + ")");
            }
        }
 private void AcceptClients()
 {
     try
     {
         Listener.Start();
         while (Running)
         {
             ProcessClient(Listener.AcceptTcpClient());
         }
     }
     catch
     {
         //nothing
     }
 }
Exemplo n.º 21
0
        public Task StartAsync()
        {
            Listener.Start();

            return(Task.Run(() =>
            {
                while (true)
                {
                    var client = Listener.AcceptTcpClient();
                    var remote = ((IPEndPoint)client.Client.RemoteEndPoint).ToString();
                    Console.WriteLine("Client connected: " + remote);
                    var connection = new TcpConnection(client, remote);
                    Connections.Add(connection);
                }
            }));
        }
Exemplo n.º 22
0
        protected override void ListenOnNewClients()
        {
            Listener.Start();

            while (true)
            {
                TcpClient connectedClient = Listener.AcceptTcpClient();
                var       sslStream       = ProcessClient(connectedClient);

                var client = HandleNewConnectedClient(connectedClient, sslStream);

                Clients.Add(client);
                OnClientConnected(new ClientConnectedEventArgs(client));
                Log.Info("New Client connected (IP: " + connectedClient.Client.RemoteEndPoint + ")");
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Accepts pending client connections and begins listening for packets on each accepted client.
        /// </summary>
        private void Accept()
        {
            running = true;
            if (StartedEvent != null)
            {
                StartedEvent(this);
            }

            while (Status)
            {
                if (!Listener.Pending())
                {
                    continue;
                }

                TcpClientHandler client = (ClientCreatedEvent != null) ? ClientCreatedEvent(Binder, this, ClientTimeout) : new TcpClientHandler(Binder, this, ClientTimeout);
                client.Receiver  = Listener.AcceptTcpClient();
                client.Connected = true;

                if ((ClientMap.Count <= MaxConnections && MaxConnections >= 0) || MaxConnections <= 0)
                {
                    TcpClient receiver = client.Receiver;
                    receiver.LingerState = new LingerOption(false, 0);
                    receiver.NoDelay     = true;
                    client.Stream        = receiver.GetStream();
                    ClientMap.Add(client.Socket, client);
                    ThreadPool.QueueUserWorkItem(thread => Handle(client));
                }
                else
                {
                    if (ClientOverflowEvent != null)
                    {
                        ThreadPool.QueueUserWorkItem(thread => ClientOverflowEvent(client));
                    }
                    client.Close();
                }
            }

            if (ClosedEvent != null)
            {
                ClosedEvent(this);
            }
            running = false;
            Close();
        }
Exemplo n.º 24
0
        private void Listening()
        {
            IsListening = true;
            while (IsListening && Listener != null)
            {
                bool pending = false;
                try
                {
                    pending = Listener.Pending();
                }
                catch
                {
                    pending = false;
                }


                if (pending)
                {
                    TcpClient client = null;
                    try
                    {
                        client = Listener.AcceptTcpClient();
                    }
                    catch
                    {
                        break;
                    }

                    if (client != null)
                    {
                        ConnectedClient newClient = new ConnectedClient(client);
                        Clients.Add(newClient);
                        newClient.StartListening();
                        newClient.OnNewResponseFromClient += newClient_OnNewResponseFromClient;
                    }
                }

                // detecter les déco :
                List <ConnectedClient> clients2BeRemoved = new List <ConnectedClient>(Clients.Where(x => !x.TcpClient.Connected).ToList());
                foreach (ConnectedClient client in clients2BeRemoved)
                {
                    Clients.Remove(client);
                }
            }
        }
Exemplo n.º 25
0
        public async void Start()
        {
            await Task.Run(() => {
                Listener.Start();
                while (true)
                {
                    _main.WriteConsole("In attesa di connessione...");


                    //waiting for connection
                    TcpClient client = Listener.AcceptTcpClient();
                    string tmp       = "client" + (ClientConnessi.Count + 1);
                    ClientConnessi.Add(tmp, client);

                    _main.WriteConsole("nuova connessione con: " + client.Client.LocalEndPoint.ToString());
                }
            });
        }
Exemplo n.º 26
0
        //public void AcceptTelnetConnection()
        //{
        //    while (true)
        //    {
        //        TcpClient client = null;
        //        client = TelnetListener.AcceptTcpClient();
        //        try
        //        {
        //            client.Client.Send(ASCIIEncoding.ASCII.GetBytes("Welcome to my Telnet!\n"));              // let the attacker think there's a telnet service open on port 23.
        //        }
        //        catch (Exception)
        //        {
        //            continue;
        //        }
        //        TelnetClients.Add(client);
        //        Console.WriteLine("Telnet Client " + ((IPEndPoint)TelnetClients.Last().Client.RemoteEndPoint).Address.ToString() + " has connected!");
        //    }
        //}

        public void AcceptConnections()
        {
            while (true)
            {
                TcpClient client = null;
                client = Listener.AcceptTcpClient();
                try
                {
                    client.Client.Send(ASCIIEncoding.ASCII.GetBytes("Please enter your password: "******"Client " + ((IPEndPoint)Clients.Last().Client.RemoteEndPoint).Address.ToString() + " has connected!");
            }
        }
Exemplo n.º 27
0
        private TcpClient BeginRunServer(TcpClient tcpClient)
        {
            if (tcpClient is null)
            {
                return(null);
            }
            else if (!tcpClient.Connected)
            {
                tcpClient = Listener.AcceptTcpClient();
                RunServerDelegate serverDelegate = new RunServerDelegate(BeginRunServer);
                serverDelegate.BeginInvoke(new TcpClient(), RunServerCallback, new object[] { serverDelegate });
                this.EndPointHistory.Add(new Tuple <IPAddress, DateTime, bool>(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address, DateTime.Now, true));
                Console.WriteLine("Połączenie: \t" + ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString() + " : " + DateTime.Now.ToString());
            }
            NetworkStream str = tcpClient.GetStream();

            byte[] buffer  = new byte[BufferSize];
            string message = String.Empty;

            try
            {
                str.Read(buffer, 0, BufferSize);
                message = Encoding.ASCII.GetString(buffer).Trim().Replace("\0", String.Empty);
                int    number = int.Parse(message);
                string silnia = this.Silnia(number).ToString();
                str.Write(Encoding.ASCII.GetBytes(silnia), 0, silnia.Length);
            }
            catch (IOException)
            { }
            catch (FormatException formatEx)
            {
                if (message.Trim() == "q")
                {
                    this.EndPointHistory.Add(new Tuple <IPAddress, DateTime, bool>(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address, DateTime.Now, true));
                    Console.WriteLine("Rozłączenie: \t" + ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString() + " : " + DateTime.Now.ToString());
                    tcpClient.Close();
                }
            }

            return(tcpClient);
        }
Exemplo n.º 28
0
        private void HandleConnections()
        {
            IsRunning = true;

            while (IsRunning)
            {
                if (Listener == null)
                {
                    break;
                }

                TcpClient tcp = Listener.AcceptTcpClient();

                Task.Factory.StartNew(() =>
                {
                    AcceptClient(tcp);
                });
            }

            Stop();
        }
Exemplo n.º 29
0
        private void ReceiveThreadFunction()
        {
            try
            {
                Listener.Start();
                byte[] bytes = new byte[256];

                while (true)
                {
                    var client = Listener.AcceptTcpClient();
                    var stream = client.GetStream();

                    int count = stream.Read(bytes, 0, bytes.Length);
                    if (count != 0)
                    {
                        string data  = Encoding.ASCII.GetString(bytes, 0, count);
                        var    parts = data.Split(':');
                        switch (parts[0])
                        {
                        case "+":
                            Regist(parts[1], int.Parse(parts[2]), int.Parse(parts[3]), parts[4]);
                            break;

                        case "-":
                            Unregist(parts[1], int.Parse(parts[2]), int.Parse(parts[3]), parts[4]);
                            break;
                        }
                    }
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Host.Logger.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                Listener.Stop();
            }
        }
Exemplo n.º 30
0
 public void Listen()
 {
     try
     {
         Listener.Start();
         _containerInterfaces.Logger.LogInformation("Server Start listen");
         while (true)
         {
             TcpClient client = Listener.AcceptTcpClient();
             Thread    thread = new Thread(() =>
             {
                 SeverHandler socketHandler = new SeverHandler(client, AllChatDetails, _containerInterfaces);
                 socketHandler.Run();
             });
             thread.Start();
         }
     }
     catch (Exception e)
     {
         Listener.Stop();
     }
 }