public async void Start() { try { Listener.Start(); Running = true; } catch (Exception e) { Console.WriteLine(String.Format("Error occured during server starting: {0}", e.Message)); } while (Running) { try { var client = await Listener.AcceptTcpClientAsync(); process(client); } catch (Exception e) { Console.WriteLine(String.Format("Error occured during client connecting: {0}", e.Message)); } } }
public async Task RunServer() { Listener.Start(); while (true) { _ = await Listener.AcceptTcpClientAsync().ContinueWith(async(t) => { byte[] buffer = new byte[1024]; GPSUser user = new GPSUser(t.Result); while (true) { string input = await getUserInput(user.client, buffer); Array.Clear(buffer, 0, buffer.Length); //Console.WriteLine($"CLIENT: {input}"); _ = Task.Run(async() => { string response = ""; try { response = await processCommand(user, input); } catch (Exception ex) { throw new Exception(ex.Message); } //.WriteLine($"SERVER: {response}"); await Send(user.client, response); }); } }); } }
/// <summary> /// Accepts the new TCP connections until cancelled. /// </summary> private async Task AcceptLoopAsync() { while (true) { TcpClient client; try { client = await Listener.AcceptTcpClientAsync(); } catch { if (!CancellationTokenSource.IsCancellationRequested) { await Session.RemoveTunnelAsync(this); } break; } var connection = new TcpServerConnection(Id, Session, client); try { await Session.AddConnection(connection, CancellationTokenSource.Token); await connection.StartAsync(); } catch { System.Diagnostics.Debug.WriteLine("Failed to add connection for new TCP client."); } } }
protected virtual async Task OpenSocketAsync() { await StartListeningAsync(); Logger.LogDebug($"Server {Name} is waiting for connection on port {Port} at {IpAddress}..."); // use Task.Run to pass the cancellation token so the Listener stops when the Token is cancelled. Client = await Task.Run(() => Listener?.AcceptTcpClientAsync(), StopToken.Token); }
public async Task Connect(CancellationToken ct) { ct.Register(() => Listener.Stop()); Client = await Listener.AcceptTcpClientAsync(); var stream = Client.GetStream(); Reader = new StreamReader(stream); Writer = new StreamWriter(stream); }
Task _Start() { return(Task.Run(async() => { Listener.Start(); while (!IsClosed) { TcpClient client = await Listener.AcceptTcpClientAsync(); _AddClient(client); } })); }
private void SocketConnectHandler() { while (IsRunning) { var clientTask = Listener.AcceptTcpClientAsync(); if (clientTask.Result != null) { var socketClient = new ConnectedClientTcpHandler(clientTask.Result); Log.Info($"Client {socketClient.ConnectionId} connected."); _clientsByConnectionId.Add(socketClient.ConnectionId, socketClient); ThreadPool.QueueUserWorkItem(ConnectedClientTcpHandler.RecievePacketWorker, socketClient); } } }
/// <summary> /// Starts listen. /// </summary> public async void Start(params object[] args) { while (!Stopped) // listen loop { TcpClient client = null; // define client to handle { client = await Listener.AcceptTcpClientAsync().ConfigureAwait(false); } var handler = ((T)Activator.CreateInstance(typeof(T), args)); { handler.Bind(client).HandleAsync(); } } }
private async Task HandleClientsRequest() { while (!cToken.Token.IsCancellationRequested) { try { TcpClient client = await Task.Run(() => Listener.AcceptTcpClientAsync(), cToken.Token); Task.Run(() => ProcessClientRequest(client), cToken.Token); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
async Task <Data> AcceptClient() { Logger.Instance.Log("Waiting for a connection"); TcpClient client; try { client = await Listener.AcceptTcpClientAsync(); } catch (Exception) { client = null; } return(new Data { TcpClient = client }); }
//начинаем слушать в отдельной нити private async void Startup() { Listener.Start(); while (true) { TcpClient client = await Listener.AcceptTcpClientAsync(); if (mutex.WaitOne()) { PeerBaseContainer newSlave = new PeerBaseContainer(Guid.NewGuid(), client); byte[] bytes = newSlave.Guid.ToByteArray(); newSlave.Client.GetStream().Write(bytes, 0, bytes.Length); Workers.Add(newSlave); mutex.ReleaseMutex(); } } }
public Task AceitarClientes(CancellationToken cancellationToken) { return(Task.Run(async() => { while (true) { Logger.LogInformation($"Waiting for client in ip:port tcp: {TcpServerOptions.IP}:{TcpServerOptions.Port}..."); var clientTask = await Listener.AcceptTcpClientAsync(); ServiceClient client = new ServiceClient() { Client = clientTask, ServiceName = Guid.NewGuid().ToString(), Name = $"Servico{Collection.Count + 1}" }; Collection.Add(client); Logger.LogDebug($"Someone connected!!! {client.Name}"); Task task = new Task(async() => await Handle_clients(client.ServiceName).ConfigureAwait(false), cts.Token); task.Start(); Tasks.Add(task); } }, cancellationToken)); }
/// <summary> /// Conecta el servicio de escucha /// </summary> private async void StartListener() { // Si no existe el objeto de escucha, lo crea if (Listener == null) { Listener = new TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Server.IP), Server.Port)); } // Inicializa el listener Listener.Start(); // Mientras continúe conectado while (IsConnected) { try { TcpClient objTcpclient = await Listener.AcceptTcpClientAsync().ConfigureAwait(false); // Trata el cliente HandleClient(objTcpclient); } catch (Exception objException) { System.Diagnostics.Debug.WriteLine("Excepción: " + objException.Message); } } }
public static void Listen() { if (Listener == null || !Accept) { return; } // Continue listening. while (true) { Console.WriteLine("Waiting for client..."); var clientTask = Listener.AcceptTcpClientAsync(); if (clientTask.Result == null) { continue; } new Task(delegate { WorkWithClient(clientTask.Result); }).Start(); } }
public async Task StartAsync() { Listener.Start(); Console.WriteLine("Server started"); ICollection <Task> processingTasks = new List <Task>(); try { while (KeepAlive) { Console.WriteLine("Waiting for client to connect"); var client = await Listener.AcceptTcpClientAsync(); processingTasks.Add(ProcessClient(client)); } } finally { await Task.WhenAll(processingTasks); Console.WriteLine("All pending connections have been closed, closing server in 5 seconds"); await Task.Delay(5000); } }
public void Start(Action <Stack <MidFunc> > middlewareStackAction) { Task.Run(() => { Listener.Start(); while (!CancellationSource.IsCancellationRequested) { if (Listener.Pending()) { Listener.AcceptTcpClientAsync() .ContinueWith(async(tcpClientTask) => { if (tcpClientTask.IsCompleted && tcpClientTask.Result != null) { using (var tcpClient = tcpClientTask.Result) using (var netStream = tcpClient.GetStream()) { var middlewareStack = new Stack <MidFunc>(); middlewareStackAction.Invoke(middlewareStack); var application = new StompPipeline(middlewareStack); while (!CancellationSource.IsCancellationRequested && tcpClient.Connected) { var frame = await Parser .ReadStompFrame(netStream, CancellationSource.Token) .UnWrapFrame(); var environment = new Dictionary <string, object> { ["stomp.requestMethod"] = frame.Command, ["stomp.requestHeaders"] = frame.Headers, ["stomp.requestBody"] = frame.Body, ["stomp.responseMethod"] = null, ["stomp.responseHeaders"] = new Dictionary <string, string>().ToImmutableArray(), ["stomp.responseBody"] = new byte[0].ToImmutableArray(), ["stomp.terminateConnection"] = false }; var responseFrame = await application.Process(environment); if (responseFrame != null) { Parser.WriteStompFrame(netStream, responseFrame); var terminatingCommands = new[] { StompCommand.DISCONNECT, StompCommand.ERROR }; if (terminatingCommands.Contains(responseFrame.Command)) { break; } } } } } }); } else { Thread.Sleep(1); } } }); }
private async void _listen() { bool connections = true; var clientTask = Listener.AcceptTcpClientAsync(); if (clientTask.Result != null) { ClientsCount++; var client = clientTask.Result; Console.WriteLine("Client connected. ip: {0}\n", client.Client.RemoteEndPoint.ToString()); try { await Task.Run(async() => { int loggedType = 0; while (connections && loggedType == 0) { try { string response = ReceiveMessage(client, loggedType); switch (response.Substring(0, 4)) { case "0005": SendMessage(client, response + "<EOM>"); Console.WriteLine("Sent to {0}: {1}", client.Client.RemoteEndPoint.ToString(), response + "<EOM>"); connections = false; break; default: loggedType = int.Parse((response.Split(new string[] { "<EOP>" }, StringSplitOptions.None)[1].Split(new string[] { "<EOR>" }, StringSplitOptions.None))[0]); Clients.Add(client, loggedType); if (!SendMessage(client, response + "<EOM>")) { connections = false; } Console.WriteLine("Sent to {0}: {1}", client.Client.RemoteEndPoint.ToString(), response + "<EOM>"); break; } } catch (IOException) { connections = false; } catch (Exception ex) { connections = false; Console.WriteLine(ex.ToString()); } } while (connections) { try { string response = ReceiveMessage(client, loggedType); switch (response.Substring(0, 4)) { case "0003": string[] updatingClients = response.Split('#'); if (!SendMessage(client, updatingClients[0] + "<EOM>")) { connections = false; Clients.Remove(client); } Console.WriteLine("Sent to {0}: {1}", client.Client.RemoteEndPoint.ToString(), updatingClients[0] + "<EOM>"); foreach (KeyValuePair <TcpClient, int> connected in Clients) { if (updatingClients[1].Contains(connected.Value.ToString())) { await Task.Run(() => SendMessage(connected.Key, updatingClients[2] + "<EOM>")); Console.WriteLine("Sent update to {0}: {1}", connected.Key.Client.RemoteEndPoint.ToString(), updatingClients[2] + "<EOM>"); } } break; case "0000": connections = false; Clients.Remove(client); break; case "0004": if (!SendMessage(client, response + "<EOM>")) { connections = false; Clients.Remove(client); } Console.WriteLine("Sent to {0}: {1}", client.Client.RemoteEndPoint.ToString(), response + "<EOM>"); break; case "0002": if (!SendMessage(client, response.Substring(9) + "<EOM>")) { connections = false; Clients.Remove(client); } Console.WriteLine("Sent to {0}: {1}", client.Client.RemoteEndPoint.ToString(), response.Substring(9) + "<EOM>"); break; } } catch (IOException) { connections = false; } catch (Exception ex) { connections = false; Console.WriteLine(ex.ToString()); } } }); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.WriteLine("Closing connection. {0} connected at the moment.", --ClientsCount); try { client.Dispose(); } catch (InvalidOperationException) { } finally { client.Close(); } } } }