Ejemplo n.º 1
0
        private void _OnClientConnect(IAsyncResult ar)
        {
            try
            {
                TcpClient Client = Listener.EndAcceptTcpClient(ar);
                if (ConnectedClients.Count >= _MaxConnections || _Parent.BannedIps.Contains(((IPEndPoint)Client.Client.RemoteEndPoint).Address.ToString()))
                {
                    Console.WriteLine($"[Server]Denied {((IPEndPoint)Client.Client.RemoteEndPoint).Address.ToString()}"); Client.Close(); Listener.BeginAcceptTcpClient(_OnClientConnect, Listener);
                }
                else
                {
                    ClientObject ClientObject = new ClientObject()
                    {
                        TcpClient = Client, Buffer = new byte[_BufferSize]
                    };

                    ConnectedClients.Add(Client);
                    _Parent.NotifyClientConnected(Client);

                    Client.GetStream().BeginRead(ClientObject.Buffer, 0, ClientObject.Buffer.Length, _OnDataReceive, ClientObject);
                    Listener.BeginAcceptTcpClient(_OnClientConnect, Listener);
                }
            }
            catch (Exception ex) { if (_Parent.IsRunning)
                                   {
                                       _Parent.NotifyOnError(ex);
                                   }
            }
        }
Ejemplo n.º 2
0
        public Client ConnectToClient(string username)
        {
            if (IsUserConnected(username))
            {
                var user = GetUser(username);

                var tcpClient = new TcpClient();
                tcpClient.Connect(user.Address, user.Port);

                var client = new Client(tcpClient)
                {
                    Username = username
                };
                ConnectedClients.Add(client);

                ClientConnected?.Invoke(this, new ConnectionEventArgs(client));

                SendToServer($"connectedto {username}");

                StartReceive(client);

                return(client);
            }

            return(null);
        }
        /// <summary>
        /// Handle the "register" command
        /// </summary>
        /// <param name="command">Command to parse and execute</param>
        /// <param name="response">Message object to send to the user</param>
        private void HandleRegisterCommand(Command command, Message response)
        {
            // Check if user is already authenticated
            if (_user != null)
            {
                response.Type    = MessageType.Error;
                response.Content = "Cannot create accounts while logged in.";
                return;
            }

            // Attempt to create user
            _user = AuthenticationService.CreateUser(command.Arguments[0], command.Arguments[1]);

            if (_user == null)
            {
                response.Type    = MessageType.Error;
                response.Content = "Credentials already in use.";
            }
            else
            {
                // Add client to list of connected clients
                ConnectedClients.Add(_user, _tcpClient);

                response.Type    = MessageType.Info;
                response.Content = $"Account created, you are now logged in as {_user.Username}.";
            }
        }
Ejemplo n.º 4
0
        public void UpdateGuiWithNewMessage(string message)
        {
            //switch thread to GUI thread to write to GUI       // Prof: sorgt dafür, dass der Thread in der GUI ausgeführt wird
            //damit es gleichzeitig abläuft
            //(Dispatcher extra erstellen => Render (Hintergrund) und GUI Threads => aktualisieren GUI)

            App.Current.Dispatcher.Invoke(() =>
            {
                string name = message.Split(':')[0];
                if (!ConnectedClients.Contains(name))
                {//not in list => add it
                    ConnectedClients.Add(name);
                }
                if (message.Contains("@quit"))
                {
                    server.DisconnectOneClient(name);
                    // Extra:
                    ConnectedClients.Remove(name);      // Client auch aus connectedClients Liste löschen
                }
                //neue Nachricht zu Nachrichten-Collection hinzufügen
                Messages.Add(message);

                // GUI informieren, dass Nachrichtenanzahl gestiegen ist
                RaisePropertyChanged("MessagesCnt");
            });
        }
Ejemplo n.º 5
0
        public void Listen()
        {
            ListenThread = new Thread(() =>
            {
                TcpListener ServerSocket = new TcpListener(IPAddress.Any, 0);
                ServerSocket.Start();

                ListeningPort = ((IPEndPoint)ServerSocket.LocalEndpoint).Port;
                SendListeningPort(ListeningPort);

                while (running)
                {
                    TcpClient tcpClient = ServerSocket.AcceptTcpClient();

                    var client = new Client(tcpClient)
                    {
                        Username = server.Receive(1024)
                    };

                    ConnectedClients.Add(client);

                    ClientConnected?.Invoke(this, new ConnectionEventArgs(client));

                    StartReceive(client);
                }

                ServerSocket.Stop();
            });

            ListenThread.Start();
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// The threaded method where the server listens for client connections. Only called from <see cref="StartClientListening"/>
        /// </summary>
        private void ListenForClients()
        {
            while (!IsDisposed)
            {
                try
                {
                    var connectedTCPClient = _listener.AcceptTcpClient();
                    var connectedClient    = new Client(connectedTCPClient);

                    connectedClient.MessageReceived += ConnectedClient_MessageReceived;

                    ConnectedClients.Add(connectedClient);
                    var eventargs = new ClientToggleEventArgs
                    {
                        ConnectedClient = connectedClient,
                        Time            = DateTime.Now
                    };
                    ClientConnected?.Invoke(this, eventargs);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.Interrupted)
                    {
                        break;
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }
        protected override void OnClientConnect(IAsyncResult result)
        {
            try
            {
                IClientMetadata state;
                int             id;

                lock (ConnectedClients)
                {
                    id = !ConnectedClients.Any() ? 1 : ConnectedClients.Keys.Max() + 1;

                    state = new ClientMetadata(((Socket)result.AsyncState).EndAccept(result), id);
                    CanAcceptConnections.Set();

                    ConnectedClients.Add(id, state);
                }

                //If the server shouldn't accept the IP do nothing.
                if (!IsConnectionAllowed(state))
                {
                    Log("A blacklisted ip tried to connect to the server: ipv4:" + state.RemoteIPv4 + " ipv6: " + state.RemoteIPv6);
                    lock (ConnectedClients)
                    {
                        ConnectedClients.Remove(id);
                    }
                    return;
                }

                Task.Run(() =>
                {
                    var stream = new NetworkStream(state.Listener);

                    //Create SslStream
                    state.SslStream = new SslStream(stream, false, AcceptCertificate);

                    var success = Authenticate(state).Result;

                    if (success)
                    {
                        RaiseClientConnected(state);
                        Receive(state);
                    }
                    else
                    {
                        lock (ConnectedClients)
                        {
                            ConnectedClients.Remove(id);
                        }
                        Log("Unable to authenticate server.");
                    }
                }, new CancellationTokenSource(10000).Token);
            }
            catch (Exception ex)
            {
                CanAcceptConnections.Set();
                RaiseLog(ex);
                RaiseErrorThrown(ex);
            }
        }
Ejemplo n.º 9
0
 // Peer's operation.
 public void AddConenectPeer(Guid guid, ServerPeer peer)
 {
     if (!ConnectedClients.ContainsKey(guid))
     {
         ConnectedClients.Add(guid, peer);
         ServerApp.Logger.Info("[ActorManager]Add peer linked. " + guid);
     }
 }
        /// <summary>
        /// Handle the "login" command
        /// </summary>
        /// <param name="command">Command to parse and execute</param>
        /// <param name="response">Message object to send to the user</param>
        private void HandleLoginCommand(Command command, Message response)
        {
            // Try authentication
            var authUser = AuthenticationService.AuthenticateUser(command.Arguments[0], command.Arguments[1]);

            // Check if authentication succeeded
            if (authUser == null)
            {
                response.Type    = MessageType.Error;
                response.Content = "Wrong credentials.";
                Net.SendMessage(_tcpClient.GetStream(), response);
                return;
            }

            // Check if a client is already connected to this account
            foreach (var user in ConnectedClients.Keys)
            {
                if (user.Username == authUser.Username)
                {
                    response.Type    = MessageType.Error;
                    response.Content = "Another client is already connected to this account";
                    Net.SendMessage(_tcpClient.GetStream(), response);
                    return;
                }
            }

            _user = authUser;

            // Add client to list of connected clients
            ConnectedClients.Add(_user, _tcpClient);

            response.Type    = MessageType.Info;
            response.Content = $"Logged in as {_user.Username}.";
            Net.SendMessage(_tcpClient.GetStream(), response);

            // Gather unread private messages
            List <PrivateMessageRecord> privateMessages = MessageRecordService.GetPrivateMessages(_user);

            //if (privateMessages.Count == 0) return;

            // Build the private messages block
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"=== You received {privateMessages.Count} private messages during your absence ===");
            foreach (var message in privateMessages)
            {
                sb.AppendLine($"[From: {message.Sender}] - {message.Content}");
            }
            sb.Append("=========================================");

            response.Type    = MessageType.Message;
            response.Content = sb.ToString();
            Net.SendMessage(_tcpClient.GetStream(), response);

            // Clear the list of unread private messages
            MessageRecordService.ClearPrivateMessages(_user);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Client connected to the server
        /// </summary>
        /// <param name="NewClient">The client that has conneced</param>
        protected override void ClientConnected(ClientModel NewClient)
        {
            // Jump on the dispatcher thread
            var uiContext = SynchronizationContext.Current;

            uiContext.Send(x => ConnectedClients.Add(NewClient), null);

            OnClientConnected.Invoke(NewClient);
        }
 private void OnNewSessionStarted(SessionInfo sessionInfo)
 {
     Application.Current.Dispatcher.Invoke(() =>
     {
         ConnectedClients.Add(new ConnectedClientDisplayData(sessionInfo.SessionId.ToString(),
                                                             sessionInfo.CreationTime.ToString(),
                                                             sessionInfo.ClientAddress.ToString()));
     });
 }
Ejemplo n.º 13
0
        private void periodicActivityCheck(object myObject, EventArgs myEventArgs)
        {
            //ACCEPT CONNECTIONS
            Socket tempSocket = tcp.tcp_acceptConnection();

            if (tempSocket != null)
            {
                Client client = new Client();
                client.ConnectionSocket = tempSocket;
                ConnectedClients.Add(client);
                txt_clients.Text = ConnectedClients.Count.ToString();
            }

            //RECIEVE MESSAGES
            for (int i = 0; i < ConnectedClients.Count; i++)
            {
                Messages.MESSAGE msg = tcp.receiveMessage(ConnectedClients[i].ConnectionSocket);
                #region MESSAGE DECODER
                switch (msg.msgID)
                {
                //Handle Error Message (Closed connection)
                case -1:
                    ConnectedClients.RemoveAt(i);
                    txt_clients.Text = ConnectedClients.Count.ToString();
                    txt_output.AppendText("Player Disconnected \n");
                    updatePlayersList();
                    break;

                case 0:
                    break;

                //Initialise player
                case 1:
                    decoder.initialiseClient(msg, ConnectedClients[i]);
                    updatePlayersList();
                    decoder.updateAllPlayersInfo();
                    break;

                //Request to invite player recieved
                case 4:
                    txt_output.AppendText("recieved request \n");
                    decoder.inviteClient(ConnectedClients[i].ClientID, msg);
                    break;

                //invitation response recieved
                case 6:
                    decoder.invitationResponse(msg);
                    break;

                default:     //pass message to appriopriate game sessession
                    getGameSession(msg.gameSession).getMessage(msg, ConnectedClients[i].ClientID);
                    break;
                }
                #endregion MESSAGE DECODER
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Opens a port for receiving incoming connections from a client white-list
        /// </summary>
        /// <param name="validClients">Client white list</param>
        public void Listen(ISet <INetworkNode> validClients)
        {
            if (IsConnectionless)
            {
                throw new InvalidOperationException("Cannot establish a connection in a connectionless protocol");
            }
            if (Self.Socket == null)
            {
                Self.Socket = new Socket(AddressScheme, SocketType.Stream, Protocol);
            }

            Self.Socket.Bind(new IPEndPoint(IPAddress.Any, Self.ListeningPort));
            Self.Socket.Listen(int.MaxValue);
            while (true)
            {
                Socket newConn = null;
                if (ListenTimeOut <= 0)
                {
                    newConn = Self.Socket.Accept();
                }
                else
                {
                    Thread listenerThread = new Thread(() => newConn = Self.Socket.Accept());
                    listenerThread.Start();
                    listenerThread.Join(ListenTimeOut);
                    if (listenerThread.ThreadState != ThreadState.Stopped)
                    {
                        listenerThread.Abort();
                    }
                }
                if (newConn == null)
                {
                    break; //timed out
                }
                else
                {
                    INetworkNode client = Util.Container.CreateInstance <INetworkNode>();
                    client.Address = (newConn.RemoteEndPoint as IPEndPoint).Address.GetAddressBytes();
                    client.Socket  = newConn;
                    //check if it is a valid client
                    if (validClients.Contains(client))
                    {
                        Thread receiverThread = new Thread(new ParameterizedThreadStart(MessageListenerAction));
                        receiverThread.Start(client);
                        ConnectedClients.Add(client, receiverThread);
                    }
                    else
                    {
                        //disconnect and raise an exception
                        newConn.Disconnect(false);
                        throw new SecurityException($"An unauthorized address: {(newConn.RemoteEndPoint as IPEndPoint).Address} tried to connect to server");
                    }
                }
            }
        }
        private void ConnectionStateChangedCallback(IEnumerable <string> connectedClients)
        {
            ConnectedClients.Clear();
            foreach (var connectedClient in connectedClients)
            {
                ConnectedClients.Add(new ListViewItemViewModel {
                    Text = string.Format("Client connected from IP: {0}", connectedClient)
                });
            }

            OnPropertyChanged("ConnectedClients");
        }
 public static bool AddClient(Client client)
 {
     if (!ConnectedClients.Any(tmp_client => tmp_client.ip == client.ip))
     {
         ConnectedClients.Add(client);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 17
0
        private void OnNotifyAvailableClientsRequest(IResonanceTransporter transporter, ResonanceMessage <NotifyAvailableClientsRequest> request)
        {
            InvokeUI(() =>
            {
                ConnectedClients.Clear();

                foreach (var client in request.Object.Clients)
                {
                    ConnectedClients.Add(client);
                }
            });
        }
        protected override void OnClientConnect(IAsyncResult result)
        {
            if (Token.IsCancellationRequested)
            {
                return;
            }

            CanAcceptConnections.Set();
            try
            {
                ISocketState state;

                lock (ConnectedClients)
                {
                    var id = !ConnectedClients.Any() ? 1 : ConnectedClients.Keys.Max() + 1;

                    state = new SocketState(((Socket)result.AsyncState).EndAccept(result), id);


                    //If the server shouldn't accept the IP do nothing.
                    if (!IsConnectionAllowed(state))
                    {
                        return;
                    }

                    var client = ConnectedClients.FirstOrDefault(x => x.Value == state);

                    if (client.Value == state)
                    {
                        id = client.Key;
                        ConnectedClients.Remove(id);
                        ConnectedClients.Add(id, state);
                    }
                    else
                    {
                        ConnectedClients.Add(id, state);
                    }

                    ClientConnectedInvoke(id, state);
                }

                StartReceiving(state);
            }
            catch (ObjectDisposedException ode)
            {
                InvokeErrorThrown(ode);
            }
            catch (SocketException se)
            {
                this.InvokeErrorThrown(se);
            }
        }
Ejemplo n.º 19
0
        public static void HandleNewClient(SocketClient client, string connectToChat)
        {
            ConnectedClients.Add(client.SocketId, client);
            if (!Chats.ContainsKey(connectToChat))
            {
                Chats.Add(connectToChat, new List <SocketClient>());
            }

            Chats[connectToChat].Add(client);
            ChatsClientMapping.Add(client.SocketId, connectToChat);
            connectToChat = connectToChat.Split().First();
            client.SendPacketIntoSocket($"Now you in {connectToChat} canal" + "\r\n");
        }
Ejemplo n.º 20
0
        public void PopulateClients()
        {
            ConnectedClients.Clear();

            var filter = Builders <ClientModel> .Filter.Gte(x => x.LastSeen, DateTime.Now.AddMinutes(-5));

            var onlineClients = Mongo.Get(filter).ToList();

            foreach (var c in onlineClients)
            {
                ConnectedClients.Add(c);
            }
        }
Ejemplo n.º 21
0
        public async Task ListenForClientsAsync()
        {
            while (true)
            {
                TcpClient client = await TcpListener.AcceptTcpClientAsync();

                Console.WriteLine("Accepted connection from client " + client.Client.LocalEndPoint);
                ConnectedClients.Add(client);
                Guid id = Guid.NewGuid();
                ClientIDs.Add(client, id);
                IDClients.Add(id, client);
                new Task(async() => await HandleClientAsync(client)).Start();
            }
        }
Ejemplo n.º 22
0
        protected override void OnClientConnect(IAsyncResult result)
        {
            CanAcceptConnections.Set();
            try
            {
                ISocketState state;
                int          id;

                lock (ConnectedClients)
                {
                    id = !ConnectedClients.Any() ? 1 : ConnectedClients.Keys.Max() + 1;

                    state = new SocketState(((Socket)result.AsyncState).EndAccept(result), id);
                }

                //If the server shouldn't accept the IP do nothing.
                if (!IsConnectionAllowed(state))
                {
                    return;
                }

                var stream = new NetworkStream(state.Listener);

                //Create SslStream
                state.SslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(AcceptCertificate));

                Task.Run(() =>
                {
                    var success = Authenticate(state).Result;

                    if (success)
                    {
                        lock (ConnectedClients)
                        {
                            ConnectedClients.Add(id, state);
                        }
                        ClientConnectedInvoke(id, state);
                        StartReceiving(state);
                    }
                    else
                    {
                        throw new AuthenticationException("Unable to authenticate server.");
                    }
                }, new CancellationTokenSource(10000).Token);
            }
            catch (SocketException se)
            {
                throw new Exception(se.ToString());
            }
        }
Ejemplo n.º 23
0
        private void OnServiceDiscovered(object sender, ResonanceDiscoveredServiceEventArgs <ResonanceSignalRDiscoveredService <DemoServiceInformation>, DemoServiceInformation> e)
        {
            if (e.DiscoveredService.DiscoveryInfo.ServiceId != _service.ServiceInformation.ServiceId)
            {
                InvokeUI(() =>
                {
                    ConnectedClients.Add(e.DiscoveredService.DiscoveryInfo);

                    if (SelectedClient == null)
                    {
                        SelectedClient = e.DiscoveredService.DiscoveryInfo;
                    }
                });
            }
        }
Ejemplo n.º 24
0
        public ServerViewModel(IWCFHostService hostService, IUnitOfWork db, ISettingsService settingsService, IDialogService dialogService)
        {
            this.hostService     = hostService;
            this.db              = db;
            this.settingsService = settingsService;
            this.dialogService   = dialogService;

            Client = new ChatWCFService.Client(settingsService.Name);
            Port   = settingsService.Port;
            hostService.ClientConnected += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    ConnectedClients.Add(e.Client);
                    Notifications.Add(new Notification($"Client {e.Client.Name} connected", DateTime.Now, NotificationType.ClientConnected));
                });
            };
            hostService.ClientDisconneced += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    var client = ConnectedClients.Where(c => c.Name == e.Client.Name).FirstOrDefault();
                    ConnectedClients.Remove(client);
                    Notifications.Add(new Notification($"Client {e.Client.Name} disconnected", DateTime.Now, NotificationType.ClientDisconnected));
                });
            };
            hostService.MessageReceived += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => {
                    Messages?.Add(new Model.Message(e.Message));
                });
            };

            DispatcherHelper.RunAsync(async() =>
            {
                var messages = (await db.Messages.GetAll()).Select(m => new Model.Message(m));
                foreach (var message in messages)
                {
                    Messages.Add(message);
                }
            });
            Messenger.Default.Register <NotificationMessage>(this, (m) => {
                switch (m.Notification)
                {
                case "ServerWindowClosed": StopServer(); break;
                }
            });
        }
 private void PacketHandlerLoop()
 {
     while (!_stopping)
     {
         NewPacketStruct packetStruct;
         while (_newPackets.TryDequeue(out packetStruct))
         {
             var  stream       = new BitStream(packetStruct.Data);
             uint type         = 0;
             uint connectionId = 0;
             stream.ReadBasicHeader(ref type, ref connectionId);
             Console.WriteLine("[NetworkingServer] handling packet received from " + packetStruct.From.ToString() + ", connection id: " + connectionId + ", packet type: " + Convert.ToString((PacketType)type));
             if (type == 0)
             {
                 Console.WriteLine("[NetworkingServer] skipping invalid packet");
                 continue;
             }
             if (type == 1)
             {
                 var par2       = stream.ReadBits(32);
                 var version    = stream.ReadBits(32);
                 var punkbuster = stream.ReadBits(1);
                 var unk        = stream.ReadBits(32);
                 var pass       = stream.ReadString(32).Replace("\0", "");
                 var mod        = stream.ReadString(32).Replace("\0", "");
                 if (mod != Config.ModName)
                 {
                     SendConnectDenied(packetStruct.From, 0x24);
                 }
                 ConnectionId++;
                 var client = new NetworkingClient(this, packetStruct.From, ConnectionId);
                 if (ConnectedClients.ContainsKey(packetStruct.From))
                 {
                     ConnectedClients.Remove(packetStruct.From);
                 }
                 ConnectedClients.Add(packetStruct.From, client);
                 SendConnectAccept(packetStruct.From, ConnectionId);
                 continue;
             }
             if (!ConnectedClients.ContainsKey(packetStruct.From))
             {
                 continue;
             }
             ConnectedClients[packetStruct.From].Handle((PacketType)type, stream);
         }
         Thread.Sleep(1);
     }
 }
Ejemplo n.º 26
0
        private IClient AddNotExistClientToCollection(Socket handler)
        {
            //handler.SendFile("", null, null, T)
            var     address     = handler.RemoteEndPoint.ToString();
            IClient client      = new Client(handler, _dataConverter);
            var     foundClient = ConnectedClients.FirstOrDefault(p => p.Address == address);

            if (foundClient != null)
            {
                client = foundClient;
            }
            else
            {
                ConnectedClients.Add(client);
                client.SentMessage += OnSentMessage;
            }

            return(client);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Opens a port for receiving a limited amount of incoming connections in a connection-oriented protocol
        /// </summary>
        /// <param name="maxConnections">Maximum number of connections allowed</param>
        public void Listen(int maxConnections)
        {
            if (IsConnectionless)
            {
                throw new InvalidOperationException("Cannot establish a connection in a connectionless protocol");
            }
            if (Self.Socket == null)
            {
                Self.Socket = new Socket(AddressScheme, SocketType.Stream, Protocol);
            }

            Self.Socket.Bind(new IPEndPoint(IPAddress.Any, Self.ListeningPort));
            Self.Socket.Listen(maxConnections);
            while (true)
            {
                Socket newConn = null;
                if (ListenTimeOut <= 0)
                {
                    newConn = Self.Socket.Accept();
                }
                else
                {
                    Thread listenerThread = new Thread(() => newConn = Self.Socket.Accept());
                    listenerThread.Start();
                    listenerThread.Join(ListenTimeOut);
                    if (listenerThread.ThreadState != ThreadState.Stopped)
                    {
                        listenerThread.Abort();
                    }
                }
                if (newConn == null)
                {
                    break; //timed out
                }
                INetworkNode client = Util.Container.CreateInstance <INetworkNode>();
                client.Address = (newConn.RemoteEndPoint as IPEndPoint).Address.GetAddressBytes();
                client.Socket  = newConn;
                Thread receiverThread = new Thread(new ParameterizedThreadStart(MessageListenerAction));
                receiverThread.Start(client);
                ConnectedClients.Add(client, receiverThread);
            }
        }
Ejemplo n.º 28
0
 private void StartServer()
 {
     if (string.IsNullOrEmpty(Client.Name))
     {
         dialogService.ShowMessage("Server client name cannot be empty. Please enter the name in the settings.");
         return;
     }
     if (hostService.Start(Port, Client))
     {
         ServerStarted = true;
         var clients = hostService.GetConnectedClients();
         clients.ForEach((c) => ConnectedClients.Add(c));
         Notifications.Add(new Notification("Server started", DateTime.Now, NotificationType.ServerStarted));
     }
     else
     {
         dialogService.ShowMessage($"Failed to start the server. Check port availability.");
         Notifications.Add(new Notification("Failed to start the server. Check port availability.", DateTime.Now, NotificationType.ServerStartFailed));
     }
 }
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            try
            {
                var client = new TcpSocketClient(acceptEventArgs.AcceptSocket);
                client.Disconnected += OnClientDisconnected;
                ConnectedClients.Add(client);
                SocketAcceptd?.Invoke(new SocketAcceptEventArgs
                {
                    AcceptClient = client
                });
                Console.WriteLine($"socket accepted, remote address:{acceptEventArgs.AcceptSocket.RemoteEndPoint}");
            }
            catch (Exception ex)
            {
                LastException = ex;
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
Ejemplo n.º 30
0
        public void Connect(string _username)
        {
            Client c = new Client()
            {
                UserName = _username,
                Id       = Context.ConnectionId
            };

            ConnectedClients.Add(c);
            using (var _contextDB = new db_chatjobsityEntities())
            {
                var _discoUser = (from x in _contextDB.Disconnected
                                  orderby x.Fe_Salida descending
                                  select x).AsEnumerable().Take(50);
                var _discoUserX = (from x in _discoUser
                                   select new { UserName = x.Fe_Salida.ToString("yyyy-MM-dd HH:mm:ss") + " - " + x.UserID.ToString() }).ToList();


                Clients.All.updateUsers(ConnectedClients.Count(), ConnectedClients.Select(x => x.UserName), _discoUserX.Select(x => x.UserName));
            }
        }