protected async override Task ExecuteAsync(CancellationToken stoppingToken) { await sync.SemaphoreSlim.WaitAsync(); logger.Information("Started PlayersTcpSocketService"); TcpListener listener = StartListener(conf.ListenerIP, conf.PlayerPort); List <ConfiguredTaskAwaitable> tasks = new List <ConfiguredTaskAwaitable>(); while (!stoppingToken.IsCancellationRequested) { await sync.SemaphoreSlim.WaitAsync(); bool canConnect = !container.GameStarted; sync.SemaphoreSlim.Release(1); if (listener.Pending() && canConnect) { var acceptedClient = await listener.AcceptTcpClientAsync(); IClient tcpClient = new TcpClientWrapper(acceptedClient); var socketClient = new TcpSocketClient <Message, Message>(tcpClient, log); var handlerTask = ClientHandler(socketClient, stoppingToken).ConfigureAwait(false); tasks.Add(handlerTask); } else { await Task.Delay(Wait, stoppingToken); } } for (int i = 0; i < tasks.Count && !stoppingToken.IsCancellationRequested; ++i) { await tasks[i]; } logger.Information("Stopping PlayersTcpSocketService"); }
private async Task <TcpSocketClient <Message, Message> > ConnectGM(string ip, int port, CancellationToken cancellationToken) { TcpListener gmListener = StartListener(ip, port); while (!cancellationToken.IsCancellationRequested) { if (gmListener.Pending()) { try { Task <TcpClient> acceptTask = gmListener.AcceptTcpClientAsync(); acceptTask.Wait(cancellationToken); IClient client = new TcpClientWrapper(acceptTask.Result); return(new TcpSocketClient <Message, Message>(client, log)); } catch (OperationCanceledException) { logger.Error("Operation was canceled during GM connection."); break; } } await Task.Delay(Wait, cancellationToken); } return(null); }
private async Task DecryptHttpsTrafficAsync(TcpClientWrapper client, TcpClientWrapper forwarder, string host) { // todo: https://stackoverflow.com/questions/11740241/https-decoding-ssl-decryption // todo: https://gist.github.com/alexsandro-xpt/3190082 try { // Generate the certificate for this traffic. var serverCertificate = SslCertificate.Create(host); // Wrap the existing client stream. var clientSslStream = new SslStream(client.Stream, false); // Authenticate this proxy server using our certificate. await clientSslStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.None, false); // Update the client stream. client.Stream = clientSslStream; // Wrap the existing forwarder stream. var forwarderSslStream = new SslStream(forwarder.Stream, false); // Authenticate the forwarder as a client connecting to an SSL server. await forwarderSslStream.AuthenticateAsClientAsync(host); // Update the forwarder stream. forwarder.Stream = forwarderSslStream; } catch (Exception e) { Console.WriteLine(e); throw; } }
private static async Task RunVirtualDevice(CancellationTokenSource cts, ServiceProvider serviceProvider, string deviceName, string deviceConnectionString, IDeviceHost module) { // Keep on looking for the new streams on IoT Hub when the previous one closes or aborts. while (!cts.IsCancellationRequested) { try { // Run virtual device var device = serviceProvider.GetServices <IStreamingDevice>() .FirstOrDefault(sd => sd.StreamDeviceName.Equals(deviceName, StringComparison.InvariantCulture)); using (var deviceClient = new DeviceClientWrapper(deviceConnectionString)) { using (var clientWebSocket = new ClientWebSocketWrapper()) { using (var tcpClient = new TcpClientWrapper()) { Console.WriteLine($"{deviceName} awaiting connection..."); await module.OpenDeviceConnectionAsync(device, deviceClient, clientWebSocket, tcpClient, cts) .ConfigureAwait(false); } } } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
public void Listen(int port) { try { rsa = new RSACryptoServiceProvider(4096); tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); Console.WriteLine($"Server running on the port {port}. Waiting for new clients..."); while (true) { TcpClient tcpClient = tcpListener.AcceptTcpClient(); var tcpClientWrapper = new TcpClientWrapper(tcpClient); ClientInstance clientInstance = new ClientInstance( tcpClientWrapper, this, new Coding(new UnicodeEncoding(false, false, true))); clients.Add(clientInstance); Thread clientThread = new Thread(clientInstance.Process); clientThread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); Disconnect(); } }
public void IsSame_Test() { // Arrange var tcpClient = new TcpClientWrapper(); var clientMock1 = new Mock <ISocketClient <Message, Message> >() { DefaultValue = DefaultValue.Mock }; clientMock1.Setup(c => c.GetSocket()).Returns(tcpClient); var clientMock2 = new Mock <ISocketClient <Message, Message> >() { DefaultValue = DefaultValue.Mock }; clientMock2.Setup(c => c.GetSocket()).Returns(tcpClient); // Act bool result = tcpSocketManager.Invoke <TcpSocketManager <Message, Message>, bool>( "IsSame", new object[] { clientMock1.Object, clientMock2.Object }); // Assert Assert.True(result, "Should return true with same tcpClient"); clientMock1.Verify(c => c.GetSocket(), Times.Once(), "GetSocket from client1 should be invoked"); clientMock2.Verify(c => c.GetSocket(), Times.Once(), "GetSocket from client2 should be invoked"); }
private IGaugeApiConnection StartGaugeAsDaemon(Project gaugeProject, int minPortRange, int maxPortRange) { var slugifiedName = gaugeProject.SlugifiedName(); if (ChildProcesses.ContainsKey(slugifiedName)) { if (ChildProcesses[slugifiedName].HasExited) { KillChildProcess(slugifiedName); } else { return(ApiConnections[slugifiedName]); } } var projectOutputPath = GetValidProjectOutputPath(gaugeProject); var port = GetOpenPort(minPortRange, maxPortRange); OutputPaneLogger.Debug("Opening Gauge Daemon for Project : {0}, at port: {1}", gaugeProject.Name, port); var environmentVariables = new Dictionary <string, string> { { "GAUGE_API_PORT", port.ToString(CultureInfo.InvariantCulture) }, { "gauge_custom_build_path", projectOutputPath } }; var gaugeProcess = GaugeProcess.ForDaemon(GetProjectRoot(gaugeProject), environmentVariables); gaugeProcess.Exited += (s, e) => OutputPaneLogger.Error( $"PID {gaugeProcess.Id} has exited with exit code {gaugeProcess.ExitCode}.\nSTDOUT:\n{gaugeProcess.StandardOutput.ReadToEnd()}\nSTDERR\n{gaugeProcess.StandardError.ReadToEnd()}"); gaugeProcess.OutputDataReceived += (sender, args) => { if (args.Data.StartsWith("Gauge daemon initialized")) { _initialized = true; } }; if (!gaugeProcess.Start()) { throw new GaugeApiInitializationException(gaugeProcess.StandardOutput.ReadToEnd(), gaugeProcess.StandardError.ReadToEnd()); } gaugeProcess.BeginOutputReadLine(); OutputPaneLogger.Debug("Opening Gauge Daemon with PID: {0}", gaugeProcess.Id); WaitForColdStart(); var tcpClientWrapper = new TcpClientWrapper(port); ApiPorts.Add(slugifiedName, port); ChildProcesses.Add(slugifiedName, gaugeProcess.BaseProcess); OutputPaneLogger.Debug("PID: {0} ready, waiting for messages..", gaugeProcess.Id); return(new GaugeApiConnection(tcpClientWrapper)); }
private void EnsureConnected(TcpClientWrapper client) { Subscribers.Add(client); Subscribed?.Invoke(client); Task.Factory.StartNew(() => { while (client.State != TcpState.Closed) { ; } Subscribers.Remove(client); }); }
static void Main(string[] args) { server.Start(); Console.WriteLine("Server started..."); while (true) { TcpClientWrapper client = new TcpClientWrapper(server.AcceptTcpClient()); allClients.Add(client); Console.WriteLine($"[{DateTime.Now}]:{client.Client.Client.RemoteEndPoint.ToString()} has joined"); thread = new Thread(() => Work(client)); thread.Start(); } }
public Chat(Connection c, Parcel firstMsg) { InitializeComponent(); try { //_tokenReceivingParcels = new CancellationTokenSource(); //_clientParcel = new Parcel(firstMsg.UserName, firstMsg.TimeStamp, "", firstMsg.Colour); _client = new TcpClientWrapper(c, firstMsg); _client.ParcelArrived += _client_ParcelArrived; } catch (Exception) { Console.WriteLine("Client: Socket Exception");; } }
private void CheckUserNameAvailability() { //if tcpclient not connected - connect and send the username if (socketClient == null) { socketClient = new TcpClientWrapper(c, new Parcel(txtUserName.Text, DateTime.Now, "***Checking" + txtUserName.Text + "***Name", Color.FromName(cmbColours.SelectedItem.ToString()))); socketClient.UserAuthorized += socketClient_UserAuthorized; socketClient.UserNotAuthorized += socketClient_UserNotAuthorized; } //otherwise - send a new user name and name for registration else { socketClient.SendParcel("***Checking" + txtUserName.Text + "***Name" + txtFullName.Text); } socketClient.NewUser = true; }
private static async Task HandleForwarderAsync(TcpClientWrapper client, TcpClientWrapper forwarder, CancellationToken token) { while (!token.IsCancellationRequested && forwarder.IsConnected) { var data = await forwarder.Read(); if (data == null) { break; } // Write the raw bytes received from the forwarder to the client. client.Write(data.RawBytes); // Important Note: // Attempting to use encoding to convert the data to a string will seemingly // result in some data being lost as the proxy no longer function. } }
public void Setup() { _logger = Substitute.For <ILogger <GraphiteNotificationService> >(); _settings = Substitute.For <SettingsService>((IServiceProvider)null); _tcpWrapper = Substitute.For <TcpClientWrapper>(); _service = new GraphiteNotificationService(_logger, _settings, _tcpWrapper); _settings.Notifications_Graphite_Host.Returns("asdf"); _settings.Notifications_Graphite_Port.Returns(1234); _sentData = null; _tcpWrapper.When(t => t.SendData("asdf", 1234, Arg.Any <byte[]>())) .Do(ci => { var bytes = ci.Arg <byte[]>(); _sentData = Encoding.ASCII.GetString(bytes); }); }
public async Task HandleClientAsync(TcpClientWrapper client, CancellationToken token) { var forwarder = new TcpClientWrapper(); while (!token.IsCancellationRequested && client.IsConnected) { var data = await client.Read(); if (data == null) { break; } // If the forwarder has a connection to a server // forward the data from to the server. if (forwarder.IsConnected) { forwarder.Write(data.RawBytes); continue; } // If the forwarder is not connected, we are receiving headers. // TODO: Ensure that all the header data has been received by constantly reading until encountering "\r\n\r\n" - the header terminator. // TODO: This also means that the buffer size can be reduced etc. // Otherwise, parse the headers from the client. var headers = HttpHeader.Parse(data.ToString()); // Extract the remote address. var hasHostField = headers.Fields.ContainsKey("Host"); var hostArray = hasHostField ? headers.Fields["Host"].Split(':') : ParseUri(headers.RequestLine.Uri); var host = hostArray[0]; var port = Convert.ToInt32(hostArray.Length == 1 ? "80" : hostArray[1]); // Output the request received. Console.WriteLine($"Received {headers.RequestLine.Method} request for {host}:{port}."); // Try connect to the server. var connectionResponse = await forwarder.Connect(host, port); // If the forwarder fails to connect to the server. // Send a bad gateway response and break out of the loop. if (!connectionResponse.Success) { var exceptionMessage = connectionResponse.Message; client.WriteHeaders("HTTP/1.1 502 Bad Gateway", $"Content-Length: {exceptionMessage.Length}", "Connection: close"); client.WriteLine(exceptionMessage); break; } // If the method of the request is a connect request. // Send a connection established response to the client. if (headers.RequestLine.Method == "CONNECT") { client.WriteHeaders("HTTP/1.1 200 Connection Established"); // TODO: We may need to check if the port is 443 here. As it could be possible that the connection doesn't involve SSL. if (_decryptHttpsTraffic) { await DecryptHttpsTrafficAsync(client, forwarder, host); } } // Otherwise, forward the data sent by the client to the server. else { forwarder.Write(data.RawBytes); } // Start handling the forwarder. var task = HandleForwarderAsync(client, forwarder, token) .ContinueWith(precursorTask => forwarder.Close(), token); } }
static void Work(TcpClientWrapper client) { while (client.Client.Connected) { string tmp = client.ReadLine(); if (tmp.Contains("Type\":\"user")) //проверка на пользователя { User user = JsonConvert.DeserializeObject <User>(tmp); if (user.NeedDelete) { Message notifMessage = new Message(); notifMessage.Content = $"[{DateTime.Now}][{user.Name}] has left chat\r\n"; string jsonMessage = JsonConvert.SerializeObject(notifMessage, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } Console.WriteLine($"[{DateTime.Now}]:{client.Client.Client.RemoteEndPoint.ToString()} left"); client.Client.Client.Close(); allClients.Remove(client); userList.Data.Remove(user); string jsonUsers = JsonConvert.SerializeObject(userList, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonUsers); } } else { StreamReader readId = new StreamReader(path_user_id_file); int get_id = Convert.ToInt32(readId.ReadLine()); readId.Close(); user.Id = get_id; StreamWriter writeId = new StreamWriter(path_user_id_file); writeId.WriteLine(++get_id); writeId.Flush(); writeId.Close(); userList.Data.Add(user); string jsonUsers = JsonConvert.SerializeObject(userList, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonUsers); } Message notifMessage = new Message(); notifMessage.Content = $"[{DateTime.Now}][{user.Name}] has joined chat\r\n"; string jsonMessage = JsonConvert.SerializeObject(notifMessage, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } } } else if (tmp.Contains("Type\":\"message")) { Message message = JsonConvert.DeserializeObject <Message>(tmp); string fullMessage = $"[{DateTime.Now}][{message.Sender}]:{message.Content}\r\n"; message.Content = fullMessage; string jsonMessage = JsonConvert.SerializeObject(message, Formatting.None); foreach (var cl in allClients) { cl.WriteLine(jsonMessage); } } } }
public App() { this.clientWrapper = new TcpClientWrapper(); clientWrapper.OnReceived += OnReceived; clientWrapper.Connect(new IPEndPoint(IPAddress.Parse(Constants.SERVER_IP), Constants.AUTH_PORT)); }
public IHttpClient Create(TcpClient client) { var clientWrapper = new TcpClientWrapper(client, BufferSize, _configService.Config.Sockets.ReceiveTimeout, BufferSize, _configService.Config.Sockets.SendTimeout, BufferSize); return(new HttpClient(clientWrapper)); }
public Chat(TcpClientWrapper client) { _client = client; InitializeComponent(); }