public Server(int port) { Clients = new List <Client>(); Users = new List <User> { new User("anonymous", "", false, false) }; _listener = new TcpListener(IPAddress.Any, port); _listener.Start(); _response = new Thread(() => { while (Thread.CurrentThread.IsAlive) { var c = new Client(_listener.AcceptTcpClient(), Users[0]); Clients.Add(c); NewClientConnected?.Invoke(this, c); } }); _response.Start(); NewClientConnected += (s, c) => { c.DataRecevied += OnClientDataRecevied; c.Disconnected += (o, ca) => { try { Clients.RemoveAt(Clients.FindIndex(a => a.Id == c.Id)); } catch { } SendToAllAsRoot("#" + c.Id + " disconnected."); }; SendToAllAsRoot("#" + c.Id + " joined the chat."); }; }
public void Parse(NetIncomingMessage mes) { switch (mes.MessageType) { case NetIncomingMessageType.ConnectionApproval: mes.SenderConnection.Approve(); break; case NetIncomingMessageType.WarningMessage: Logman.Log(mes.ReadString()); break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus stat = (NetConnectionStatus)mes.ReadByte(); Logman.Log(mes.SenderEndPoint.Address.ToString() + ": " + stat.ToString(), LOG_TYPE.WARNING); if (stat == NetConnectionStatus.Connected) { Logman.Log("New client connected, broadcasting connection."); BroadcastNewConnection(mes.SenderConnection); if (NewClientConnected != null) { NewClientConnected.Invoke(mes.SenderConnection); } } break; case NetIncomingMessageType.Data: ParseData(mes); break; } }
public IClient AddClient(string name, bool displayPlayerName, bool colorAccepted) { Debug.Assert(_client == null, "Client already added"); ConsoleClient client = new ConsoleClient(name) { DisplayPlayerName = displayPlayerName, ColorAccepted = colorAccepted }; _client = client; NewClientConnected?.Invoke(client); return(client); }
/// <summary> /// Асинхронный запуск сервера /// </summary> /// <returns></returns> public Task StartAsync() { return(Task.Factory.StartNew(() => { try { if (MessageEncryptionEnabled) { Console.WriteLine($"Server run on {Port} with encryption channel"); } else { Console.WriteLine($"Server run on {Port}"); } _listener.Start(); while (true) { TcpClient client = _listener.AcceptTcpClient(); Task.Factory.StartNew(() => { var fluffyClient = new FluffyClient(client, this); AddConnectedClient(fluffyClient); StoreInit?.Invoke(fluffyClient); NewClientConnected?.Invoke(fluffyClient); fluffyClient.Disconnected += client1 => { ClientDisconnected?.Invoke(client1); }; fluffyClient.NewData += (data) => { NewData?.Invoke(fluffyClient, data); }; fluffyClient.NewPacket += (ref int id, PacketParser <Packet> parser, FluffyClient xFuffyClient) => { NewPacket?.Invoke(ref id, parser, xFuffyClient); }; }); } } catch (Exception e) { Console.WriteLine(e.Message + " " + e.StackTrace); } })); }
/// <summary> /// Starts this instance. /// </summary> public void Start() { IPEndPoint ep = new IPEndPoint(IPAddress.Parse(this.IP), port); this.listener = new TcpListener(ep); this.listener.Start(); running = true; Task task = new Task(() => { //as long as the server is running keep listening for new clients while (running) { try { TcpClient client = listener.AcceptTcpClient(); IClientHandler newHandler = new ClientHandler(client); //when a clientHandler recieve a command from the gui client, pass it to the main server newHandler.GotCommandFromGui += this.PassInfoFromClientHandlerToServer; //when a ClientHandlerCloses - remove it from the clients list newHandler.HandlerClosed += this.RemoveHandlerFromList; m_mutex.WaitOne(); //add it to the list ch.Add(newHandler); m_mutex.ReleaseMutex(); //let the main server know a new client connected NewClientConnected?.Invoke(this, newHandler); //start handeling the new client newHandler.HandleClient(); } catch (SocketException e) { this.running = false; Close(); } } }); task.Start(); }
/// <summary> /// Starts this instance. /// </summary> public void Start() { IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port); _listener = new TcpListener(ep); _listener.Start(); _loggingService.Log("Waiting for connections", EventLogEntryType.Information); Task.Run(() => { while (true) { try { // Listens for new clients. TcpClient client = _listener.AcceptTcpClient(); _loggingService.Log("Got new connection", EventLogEntryType.Information); ITcpClientHandler ch = _clientHandlerFactory.Create(client, _loggingService); NewClientConnected?.Invoke(this, new NewClientConnectedEventArgs { ClientHandler = ch }); _clientHandlersList.Add(ch); ch.GuiClientClosed += (sender, args) => _clientHandlersList.Remove((ITcpClientHandler)sender); ch.HandleClient(); } catch (SocketException) { break; } } _loggingService.Log("Server stopped", EventLogEntryType.Information); }); }
private void AcceptCallback(IAsyncResult ar) { try { // Signal the ListenTask to continue. _listenEvent.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket clientSocket = listener.EndAccept(ar); Log.Default.WriteLine(LogLevels.Debug, "Client connected from " + ((IPEndPoint)clientSocket.RemoteEndPoint).Address); // Create the state object. ClientTelnetStateObject client = new ClientTelnetStateObject(this) { ClientSocket = clientSocket, }; _clients.Add(client); // TODO: NewClientConnected will be called once protocol handshake is done // client.State = ClientStates.Connected; NewClientConnected?.Invoke(client); // clientSocket.BeginReceive(client.Buffer, 0, ClientTelnetStateObject.BufferSize, 0, ReadCallback, client); } catch (ObjectDisposedException) { // If server status is stopping/stopped: ok // else, throw if (_status != ServerStatus.Stopping && _status != ServerStatus.Stopped) { throw; } } }
private void ClientMain(object clientObject) { if (!(clientObject is TcpClient client)) { return; } bool done = false; RemoteXTMF ourRemoteClient = new RemoteXTMF(); try { // Step 1) Accept the Client var clientStream = client.GetStream(); GenerateUniqueName(ourRemoteClient); _AvailableClients.Add(ourRemoteClient); lock (this) { try { ConnectedClients.Add(ourRemoteClient); NewClientConnected?.Invoke(ourRemoteClient); } catch { } } // Start up the thread to process the messages coming from the remote xtmf new Thread(delegate() { while (!done && !_Exit) { // cycle every 500ms ~ 1/2 second try { clientStream.ReadTimeout = Timeout.Infinite; BinaryReader reader = new BinaryReader(clientStream); BinaryFormatter readingConverter = new BinaryFormatter(); while (!done && !_Exit) { var messageType = (MessageType)reader.ReadInt32(); var clientMessage = new Message(messageType); switch (messageType) { case MessageType.Quit: { done = true; return; } case MessageType.RequestResource: { var name = reader.ReadString(); clientMessage.Data = name; ourRemoteClient.Messages.Add(clientMessage); } break; case MessageType.PostProgess: { var progress = reader.ReadSingle(); clientMessage.Data = progress; ourRemoteClient.Messages.Add(clientMessage); } break; case MessageType.PostComplete: { ourRemoteClient.Messages.Add(clientMessage); } break; case MessageType.PostResource: { var data = readingConverter.Deserialize(reader.BaseStream); clientMessage.Data = data; ourRemoteClient.Messages.Add(clientMessage); } break; case MessageType.SendCustomMessage: { // Time to recieve a new custom message var number = reader.ReadInt32(); var length = reader.ReadInt32(); var buff = new byte[length]; MemoryStream buffer = new MemoryStream(buff); int soFar = 0; while (soFar < length) { soFar += reader.Read(buff, soFar, length - soFar); } ourRemoteClient.Messages.Add(new Message(MessageType.ReceiveCustomMessage, new ReceiveCustomMessageMessage() { CustomMessageNumber = number, Stream = buffer })); } break; case MessageType.WriteToHostConsole: var str = reader.ReadString(); Console.WriteLine($"{ourRemoteClient.UniqueID}\r\n{str}"); break; default: { done = true; client.Close(); } break; } } } catch { // we will get here if the connection is closed try { if (client.Connected) { continue; } } catch (ObjectDisposedException) { done = true; } } done = true; } // don't close the reader/writer since this will also close the client stream }).Start(); BinaryWriter writer = new BinaryWriter(clientStream); BinaryFormatter converter = new BinaryFormatter(); clientStream.WriteTimeout = 10000; while (!done && !_Exit) { Message message = ourRemoteClient.Messages.GetMessageOrTimeout(200); if (message == null) { message = new Message(MessageType.RequestProgress); } var nowDone = ProcessMessage(done, ourRemoteClient, writer, converter, message); Thread.MemoryBarrier(); done = done | nowDone; } done = true; } catch { } finally { done = true; lock (this) { try { client.Close(); } catch { } try { lock (ourRemoteClient) { ourRemoteClient.Connected = false; ourRemoteClient.Messages.Dispose(); ourRemoteClient.Messages = null; } lock (this) { ConnectedClients.Remove(ourRemoteClient); ClientDisconnected?.Invoke(ourRemoteClient); } } catch (Exception e) { Console.WriteLine(e.Message); } } } }
private void EndRead(IAsyncResult asyncResult) { try { var parameter = _readByteDelegate.EndInvoke(asyncResult); var size = Sender.Connection.BinaryReader.ReadInt32(); var bytes = Sender.Connection.BinaryReader.ReadBytes(size); Serializer serializer; OnlineClientInformation client; int clientId; PackageInformation packageInformation = null; if (PackageReceived != null) { packageInformation = new PackageInformation { Size = bytes.Length + 1, Timestamp = DateTime.Now, IsReceived = true } } ; switch ((FromClientPackage)parameter) { case FromClientPackage.ResponseToAdministration: case FromClientPackage.ResponseToAdministrationCompressed: var isCompressed = parameter == (byte)FromClientPackage.ResponseToAdministrationCompressed; var data = isCompressed ? LZF.Decompress(bytes, 1) : bytes; if (packageInformation != null) { packageInformation.Description = (FromClientPackage)parameter + " " + CurrentController.DescribePackage(bytes[0], data, isCompressed ? 0 : 1); } CurrentController?.PackageReceived(bytes[0], data, isCompressed ? 0 : 1); break; case FromClientPackage.ResponseLoginOpen: clientId = BitConverter.ToInt32(bytes, 0); client = _loginsPending.FirstOrDefault(x => x.Id == clientId); if (client == null) { Logger.Error((string)Application.Current.Resources["CouldNotFindClient"]); break; } _loginsPending.Remove(client); Application.Current.Dispatcher.BeginInvoke(new Action(() => { CurrentController = new ClientController(client, Sender, this); ((Commander)CurrentController.Commander).ConnectionInfo.PackageSent += _packageSentEventHandler; LoginOpened?.Invoke(this, EventArgs.Empty); })); break; case FromClientPackage.NewClientConnected: serializer = new Serializer(new[] { typeof(ClientInformation), typeof(OnlineClientInformation) }); client = serializer.Deserialize <OnlineClientInformation>(bytes); Logger.Info(string.Format((string)Application.Current.Resources["NewClientConnected"], client.IpAddress, client.Port, client.UserName)); lock (_clientListUpdateLock) Application.Current.Dispatcher.Invoke(() => ClientProvider.NewClientConnected(client)); NewClientConnected?.Invoke(this, client); break; case FromClientPackage.ClientConnected: serializer = new Serializer(new[] { typeof(ClientInformation), typeof(OnlineClientInformation) }); client = serializer.Deserialize <OnlineClientInformation>(bytes); Logger.Info(string.Format((string)Application.Current.Resources["NewClientConnected"], client.IpAddress, client.Port, client.UserName)); lock (_clientListUpdateLock) Application.Current.Dispatcher.Invoke(() => ClientProvider.ClientConnected(client)); ClientConnected?.Invoke(this, client); break; case FromClientPackage.ClientDisconnected: var disconnectedClientId = BitConverter.ToInt32(bytes, 0); if (CurrentController != null && CurrentController.Client.Id == disconnectedClientId) { CurrentController.Dispose(); CurrentController = null; } lock (_clientListUpdateLock) Application.Current.Dispatcher.Invoke( () => ClientProvider.ClientDisconnected(disconnectedClientId)); ClientDisconnected?.Invoke(this, disconnectedClientId); break; case FromClientPackage.ComputerInformationAvailable: var clientWithComputerInformationId = BitConverter.ToInt32(bytes, 0); Application.Current.Dispatcher.BeginInvoke( new Action( () => ClientProvider.ComputerInformationAvailable(clientWithComputerInformationId))); break; case FromClientPackage.PasswordsAvailable: var clientWithPasswordsId = BitConverter.ToInt32(bytes, 0); ClientProvider.PasswordsAvailable(clientWithPasswordsId); break; case FromClientPackage.GroupChanged: var newGroupNameLength = BitConverter.ToInt32(bytes, 0); var newGroupName = Encoding.UTF8.GetString(bytes, 4, newGroupNameLength); var clients = new Serializer(typeof(List <int>)).Deserialize <List <int> >(bytes, 4 + newGroupNameLength); ClientProvider.ClientGroupChanged(clients, newGroupName); Logger.Receive((string)Application.Current.Resources["GroupChanged"]); break; case FromClientPackage.ClientsRemoved: serializer = new Serializer(typeof(List <int>)); var removedClientsIds = serializer.Deserialize <List <int> >(bytes); lock (_clientListUpdateLock) Application.Current.Dispatcher.Invoke( () => ClientProvider.ClientRemoved(removedClientsIds)); if (removedClientsIds.Count == 1) { Logger.Receive((string)Application.Current.Resources["ClientRemoved"]); } else { Logger.Receive(string.Format((string)Application.Current.Resources["ClientsRemoved"], removedClientsIds.Count)); } break; case FromClientPackage.DynamicCommandsRemoved: DynamicCommandsRemoved?.Invoke(this, new Serializer(typeof(List <int>)).Deserialize <List <int> >(bytes)); break; case FromClientPackage.PluginLoaded: clientId = BitConverter.ToInt32(bytes, 0); var pluginInfo = new Serializer(typeof(PluginInfo)).Deserialize <PluginInfo>(bytes, 4); ClientProvider.ClientPluginAvailable(clientId, pluginInfo); PluginLoaded?.Invoke(this, new PluginLoadedEventArgs(clientId, pluginInfo.Guid, pluginInfo.Version, true)); break; case FromClientPackage.PluginLoadFailed: clientId = BitConverter.ToInt32(bytes, 0); PluginLoadingFailed?.Invoke(this, new PluginLoadedEventArgs(clientId, new Guid(bytes.Skip(4).Take(16).ToArray()), Encoding.ASCII.GetString(bytes.Skip(20).ToArray()), false)); break; case FromClientPackage.DataTransferProtocolResponse: if (packageInformation != null) { packageInformation.Description = "DataTransferProtocolResponse - " + DataTransferProtocolFactory.DescribeReceivedData(bytes, 0); } DataTransferProtocolFactory.Receive(bytes); break; case FromClientPackage.ResponseActiveWindow: clientId = BitConverter.ToInt32(bytes, 0); var clientViewModel = ClientProvider.Clients.FirstOrDefault(x => x.Id == clientId); if (clientViewModel != null) { clientViewModel.ActiveWindow = Encoding.UTF8.GetString(bytes, 4, bytes.Length - 4); } break; case FromClientPackage.ResponseScreenshot: clientId = BitConverter.ToInt32(bytes, 0); var clientViewModel2 = ClientProvider.Clients.FirstOrDefault(x => x.Id == clientId); if (clientViewModel2 != null) { using (var stream = new MemoryStream(bytes, 4, bytes.Length - 4)) using (var image = (Bitmap)Image.FromStream(stream)) clientViewModel2.Thumbnail = BitmapConverter.ToBitmapSource(image); } break; case FromClientPackage.DataRemoved: DataRemoved?.Invoke(this, new Serializer(typeof(List <int>)).Deserialize <List <int> >(bytes)); break; case FromClientPackage.PasswordsRemoved: var clientIds = new Serializer(typeof(List <int>)).Deserialize <List <int> >(bytes); foreach (var id in clientIds) { ClientProvider.PasswordsRemoved(id); } PasswordsRemoved?.Invoke(this, clientIds); break; case FromClientPackage.DataDownloadPackage: DownloadDataReceived?.Invoke(this, bytes); break; case FromClientPackage.StaticCommandPluginReceived: StaticCommandReceived?.Invoke(this, bytes); break; case FromClientPackage.StaticCommandPluginTransmissionFailed: StaticCommandTransmissionFailed?.Invoke(this, bytes); break; case FromClientPackage.DynamicCommandAdded: DynamicCommandAdded?.Invoke(this, new Serializer(RegisteredDynamicCommand.RequiredTypes).Deserialize <RegisteredDynamicCommand>(bytes)); break; case FromClientPackage.DynamicCommandEventsAdded: DynamicCommandEventsAdded?.Invoke(this, new Serializer(typeof(List <DynamicCommandEvent>)).Deserialize <List <DynamicCommandEvent> >( bytes)); break; case FromClientPackage.DynamicCommandStatusUpdate: DynamicCommandStatusUpdated?.Invoke(this, new DynamicCommandStatusUpdatedEventArgs(BitConverter.ToInt32(bytes, 0), (DynamicCommandStatus)bytes[4])); break; case FromClientPackage.ResponseLibraryInformation: LibraryInformationReceived?.Invoke(this, new LibraryInformationEventArgs(BitConverter.ToInt32(bytes, 0), (PortableLibrary)BitConverter.ToInt32(bytes, 4))); break; case FromClientPackage.ResponseLibraryLoadingResult: LibraryLoadingResultReceived?.Invoke(this, new LibraryInformationEventArgs(BitConverter.ToInt32(bytes, 0), (PortableLibrary)BitConverter.ToInt32(bytes, 4))); break; case FromClientPackage.ActiveCommandsChanged: ActiveCommandsChanged?.Invoke(this, new Serializer(typeof(ActiveCommandsUpdate)).Deserialize <ActiveCommandsUpdate>(bytes, 0)); break; default: throw new ArgumentOutOfRangeException(); } if (packageInformation != null) { if (string.IsNullOrEmpty(packageInformation.Description)) { packageInformation.Description = ((FromClientPackage)parameter).ToString(); } PackageReceived?.Invoke(this, packageInformation); } _readByteDelegate.BeginInvoke(EndRead, null); } catch (Exception ex) { if (!(ex is IOException) || ex.HResult != -2147024858) { LogManager.GetCurrentClassLogger().Warn(ex, "Disconnected from server"); if (Application.Current != null) { Logger.Error(string.Format((string)Application.Current.Resources["DisconnectedFromServerException"], ex.Message)); } } else if (Application.Current != null) { Logger.Warn((string)Application.Current.Resources["DisconnectedFromServer"]); } else { LogManager.GetCurrentClassLogger().Warn("NullReference"); } Dispose(); Disconnected?.Invoke(this, EventArgs.Empty); } }