private async void connectButton_Click(object sender, RoutedEventArgs e) { try { RoverAddressTextBox.IsEnabled = false; connection = new SocketConnection(); await connection.ConnectAsync(RoverAddressTextBox.Text.Trim()); GamepadService.Autopiloting = false; dispatcherTimer.Start(); settings[ROVER_ADDRESS] = RoverAddressTextBox.Text.Trim(); connectButton.Visibility = Visibility.Collapsed; disconnectButton.Visibility = Visibility.Visible; roverControl.Visibility = Visibility.Visible; } catch (Exception ex) { await this.ShowErrorAsync(ex); RoverAddressTextBox.IsEnabled = true; connection = null; } }
public async Task RunStressPingPongTest_Socket() { var endpoint = new IPEndPoint(IPAddress.Loopback, 5050); using (var server = new SocketListener()) { server.OnConnection(PongServer); server.Start(endpoint); const int SendCount = 500, ClientCount = 5; for (int loop = 0; loop < ClientCount; loop++) { using (var connection = await SocketConnection.ConnectAsync(endpoint)) { try { var tuple = await PingClient(connection, SendCount); Assert.Equal(SendCount, tuple.Item1); Assert.Equal(SendCount, tuple.Item2); Console.WriteLine($"Ping: {tuple.Item1}; Pong: {tuple.Item2}; Time: {tuple.Item3}ms"); } finally { await connection.DisposeAsync(); } } } } }
public async Task <IDuplexPipe?> CreateFastAsync(EndPoint endPoint, CancellationToken cancellationToken) { byte[]? authenticationPacket = _authenticationPacket; SocketConnection?socket = await SocketConnection.ConnectAsync(_endPoint); try { WriteAllRequests(socket.Output, endPoint, authenticationPacket); await socket.Output.FlushAsync(cancellationToken).ConfigureAwait(false); if (!await ReceiveAllResponsesAsync(socket.Input, authenticationPacket, cancellationToken)) { return(null); } return(Interlocked.Exchange(ref socket, null)); } finally { if (!(socket is null)) { socket.Dispose(); } } }
static async Task DoTheThingViaPipelines(string host, int port, string password, bool useTls, string certificateFile) { try { await Console.Out.WriteLineAsync(ShowDetails?$"resolving ip of '{host}'..." : "resolving ip of host"); var ip = (await Dns.GetHostAddressesAsync(host)).First(); await Console.Out.WriteLineAsync(ShowDetails?$"connecting to '{ip}:{port}'..." : "connecting to host"); using (var socket = await SocketConnection.ConnectAsync(new IPEndPoint(ip, port))) { IPipeConnection connection = socket; if (useTls) // need to think about the disposal story here? { connection = await Leto.TlsPipeline.AuthenticateClient(connection, new Leto.ClientOptions() { CertificateFile = certificateFile }); } await ExecuteWithTimeout(connection, password); } } catch (Exception ex) { await Console.Error.WriteLineAsync(ex.Message); } }
public async Task TestClientToServer() { var endPoint = randomIPEndPoint; var receivedTcs = new TaskCompletionSource <byte[]>(); var connections = new List <SocketConnection>(); var server = new SocketServer(); server.OnEvent += (_, e_) => { if (e_ is OnSocketAccepted) { var e = e_ as OnSocketAccepted; var connection = e.connection; connection.OnEvent += (_, e_) => { if (e_ is OnSocketReceived) { var e = e_ as OnSocketReceived; receivedTcs.SetResult(e.buffer); } }; connections.Add(connection); e.isAccept = true; } }; server.Listen(endPoint); var client = new SocketConnection(); await client.ConnectAsync(endPoint); await client.SendAsync(payloadBytes); Assert.IsTrue(payloadBytes.SequenceEqual(await receivedTcs.Task)); }
public static async Task <DuplexPipeClient> ConnectAsync(EndPoint endPoint, ILogger logger = null) { var socketConnection = await SocketConnection.ConnectAsync(endPoint, onConnected : async conn => await Console.Out.WriteLineAsync($"已连接至服务端@{endPoint}"), logger : logger); return(new DuplexPipeClient(socketConnection, logger)); }
private async Task ConnectImpl() { var endpoint = new IPEndPoint(IPAddress.Loopback, 9080); object waitForRunning = new object(); Task <string> server; lock (waitForRunning) { server = Task.Run(() => SyncEchoServer(waitForRunning, endpoint)); if (!Monitor.Wait(waitForRunning, 5000)) { Throw.Timeout("Server didn't start"); } } string actual; Log?.DebugLog("connecting..."); using var conn = await SocketConnection.ConnectAsync(endpoint, connectionOptions : SocketConnectionOptions.ZeroLengthReads).ConfigureAwait(false); var data = Encoding.ASCII.GetBytes("Hello, world!"); Log?.DebugLog("sending message..."); await conn.Output.WriteAsync(data).ConfigureAwait(false); Log?.DebugLog("completing output"); conn.Output.Complete(); Log?.DebugLog("awaiting server..."); actual = await server; Assert.Equal("Hello, world!", actual); string returned; Log?.DebugLog("buffering response..."); while (true) { var result = await conn.Input.ReadAsync().ConfigureAwait(false); var buffer = result.Buffer; Log?.DebugLog($"received {buffer.Length} bytes"); if (result.IsCompleted) { returned = Encoding.ASCII.GetString(result.Buffer.ToArray()); Log?.DebugLog($"received: '{returned}'"); break; } Log?.DebugLog("advancing"); conn.Input.AdvanceTo(buffer.Start, buffer.End); } Assert.Equal("!dlrow ,olleH", returned); Log?.DebugLog("disposing"); }
public async Task <IDuplexPipe?> CreateAsync(EndPoint endPoint, CancellationToken cancellationToken) { if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } return(await SocketConnection.ConnectAsync(endPoint).ConfigureAwait(false)); }
public async Task TestConnect() { var endPoint = randomIPEndPoint; var listener = new TcpListener(endPoint); listener.Start(); var socketConnection = new SocketConnection(); await socketConnection.ConnectAsync(endPoint); }
public async Task Start(TestType testType) { Interlocked.Increment(ref s_connectBeginCnt); SocketConnection conn = null; TcpClient client = null; switch (testType) { case TestType.Pipeline: _stopwatch.Start(); conn = await SocketConnection.ConnectAsync(_server, pipeOptions : s_pipeOptions); _protocol = new PipeFrameProtocol(conn.Input, conn.Output); break; case TestType.TcpSocket: client = new TcpClient(); _stopwatch.Start(); await client.ConnectAsync(((IPEndPoint)_server).Address, ((IPEndPoint)_server).Port); _protocol = new TcpFrameProtocol(client.Client); break; } Interlocked.Increment(ref s_connectFinishCnt); ConnectDuration = _stopwatch.Elapsed; _stopwatch.Restart(); try { for (int i = 0; i < _echoRound; i++) { Interlocked.Increment(ref s_writeBeginCnt); await _protocol.WriteAsync(_payload); Interlocked.Increment(ref s_writeFinishCnt); ReadOnlyMemory <byte> buffer = await _protocol.ReadAsync(); if (buffer.Length == 0) { return; } Interlocked.Increment(ref s_readFinishCnt); } EchoDuration = _stopwatch.Elapsed; } catch (Exception e) { Error = e; } finally { conn?.Dispose(); client?.Dispose(); } }
public void Setup() { _server = new SimpleEchoServer(PORT); _client = new TcpClient(IPAddress.Loopback.ToString(), PORT); _socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp); _socketClient.Connect(IPAddress.Loopback, PORT); _pipeServer = new PipeServer(PORT + 10); _pipeClient = SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Loopback, PORT + 10)).Result; }
public static async Task <RemoteNetworkConnection> Connect() { var socketConn = await SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 8080)); var connection = new RemoteNetworkConnection { Parser = _parser, Pipe = socketConn }; return(connection); }
//static UvTcpListener server; public static void Main(string[] args) { server = new SocketListener(); //server = new UvTcpListener(_thread,address); server.OnConnection(Server); //server.Start(); server.Start(address); client = SocketConnection.ConnectAsync(address).Result; Task recieve = Task.Run(() => ClientQueue(client)); Console.ReadLine(); }
public async Task CanCreateWorkingEchoServer_PipelineSocketServer_PipelineSocketClient() { var endpoint = new IPEndPoint(IPAddress.Loopback, 5020); const string MessageToSend = "Hello world!"; string reply = null; using (var server = new SocketListener()) { server.OnConnection(Echo); server.Start(endpoint); using (var client = await SocketConnection.ConnectAsync(endpoint)) { try { var output = client.Output.Alloc(); output.Append(MessageToSend, TextEncoder.Utf8); await output.FlushAsync(); client.Output.Complete(); while (true) { var result = await client.Input.ReadAsync(); var input = result.Buffer; // wait for the end of the data before processing anything if (result.IsCompleted) { reply = input.GetUtf8String(); client.Input.Advance(input.End); break; } else { client.Input.Advance(input.Start, input.End); } } } finally { await client.DisposeAsync(); } } } Assert.Equal(MessageToSend, reply); }
private static async Task RunLatencyTest(bool isWarmup = false) { int testCount = (isWarmup) ? 10 : 20_000; if (!isWarmup) { Console.WriteLine($"Running 1 connection latency test ({testCount} iterations"); } const int port = 15435; byte[] buffer = Encoding.UTF8.GetBytes("SOME TEST DATA!\n"); using (var server = new SimpleTcpServer(port)) { using (var client = await SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Loopback, port))) { var sw = Stopwatch.StartNew(); for (int i = 0; i < testCount; i++) { await client.Output.WriteAsync(buffer); await client.Output.FlushAsync(); var result = await client.Input.ReadAsync(); if (result.Buffer.Length != buffer.Length) { Console.WriteLine("LatencyTest for wrong response!"); break; } client.Input.AdvanceTo(result.Buffer.End); if (!isWarmup && i > 2000 && i % 2000 == 0) { var t = sw.ElapsedMilliseconds; Console.Write(" {1} r/s ({0}ms elapsed) \r", t, (int)((double)(i + 1) / ((double)t / 1000))); } } var t1 = sw.ElapsedMilliseconds; if (!isWarmup) { Console.WriteLine(" {1} r/s ({0}ms elapsed) ", t1, (int)((double)testCount / ((double)t1 / 1000))); } } } }
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments. The target address can be specified as an argument in the format [IP]:[Port].</param> internal static async Task Main(string[] args) { var address = args.Length > 0 ? args[0] : "127.0.0.1:55901"; var socketConnection = await SocketConnection.ConnectAsync(IPEndPoint.Parse(address)); var encryptor = new PipelinedXor32Encryptor(new PipelinedSimpleModulusEncryptor(socketConnection.Output, PipelinedSimpleModulusEncryptor.DefaultClientKey).Writer); var decryptor = new PipelinedSimpleModulusDecryptor(socketConnection.Input, PipelinedSimpleModulusDecryptor.DefaultClientKey); var connection = new Connection(socketConnection, decryptor, encryptor); _ = new TestClient(connection); await connection.BeginReceive(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
public async Task CanCreateWorkingEchoServer_PipelineSocketServer_PipelineSocketClient() { var endpoint = new IPEndPoint(IPAddress.Loopback, 5010); const string MessageToSend = "Hello world!"; string reply = null; using (var server = new SocketListener()) { server.OnConnection(Echo); server.Start(endpoint); using (var client = await SocketConnection.ConnectAsync(endpoint)) { var output = client.Output.Alloc(); output.Append(MessageToSend, EncodingData.InvariantUtf8); await output.FlushAsync(); client.Output.Complete(); while (true) { var result = await client.Input.ReadAsync(); // Jump of the stack because we might be in ReceiveFromSocketAndPushToWriterAsync CompleteWriter stack // and it will deadlock with Dispose await Task.Yield(); var input = result.Buffer; // wait for the end of the data before processing anything if (result.IsCompleted) { reply = input.GetUtf8String(); client.Input.Advance(input.End); break; } else { client.Input.Advance(input.Start, input.End); } } } } Assert.Equal(MessageToSend, reply); }
public static async Task <JsonRpcClient> ConnectAsync(int port) { #if false var client = new TcpClient(); await client.ConnectAsync("127.0.0.1", port); return(new JsonRpcClient(new StreamDuplexPipe(PipeOptions.Default, client.GetStream())) { Timeout = Debugger.IsAttached ? TimeSpan.FromHours(1) : TimeSpan.FromSeconds(1) }); #else var c = await SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Loopback, port)); return(new JsonRpcClient(c) { Timeout = Debugger.IsAttached ? TimeSpan.FromHours(1) : TimeSpan.FromSeconds(1) }); #endif }
public async Task TestSend() { var endPoint = randomIPEndPoint; var listener = new TcpListener(endPoint); listener.Start(); var socketConnection = new SocketConnection(); await socketConnection.ConnectAsync(endPoint); using (var client = await listener.AcceptTcpClientAsync()) { await socketConnection.SendAsync(payloadBytes); var receiveBuffer = new byte[payloadBytes.Length]; await client.GetStream().ReadAsync(receiveBuffer); Assert.IsTrue(receiveBuffer.SequenceEqual(payloadBytes)); } }
public async Task Start() { _stopwatch.Start(); Interlocked.Increment(ref ConnectBeginCnt); SocketConnection conn = await SocketConnection.ConnectAsync(_server); Interlocked.Increment(ref ConnectFinishCnt); ConnectDuration = _stopwatch.Elapsed; _stopwatch.Restart(); try { FrameProtocol.FrameProtocol protocol = new FrameProtocol.FrameProtocol(conn.Input, conn.Output); for (int i = 0; i < _echoRound; i++) { Interlocked.Increment(ref WriteBeginCnt); await protocol.WriteAsync(_payload); Interlocked.Increment(ref WriteFinishCnt); (var imo, var len) = await protocol.ReadAsync(); Interlocked.Increment(ref ReadFinishCnt); using (imo) { if (len != _payload.Length) { throw new Exception("unexpect echo result"); } } } EchoDuration = _stopwatch.Elapsed; } catch (Exception e) { Error = e; } finally { conn.Dispose(); } }
public async Task <IDuplexPipe?> CreateSlowAsync(EndPoint endPoint, CancellationToken cancellationToken) { byte[]? authenticationPacket = _authenticationPacket; SocketConnection?socket = await SocketConnection.ConnectAsync(_endPoint); try { (bool result, bool requireAuthentication) = await NegotiateAsync(socket, !(authenticationPacket is null), cancellationToken).ConfigureAwait(false); if (!result) { return(null); } if (requireAuthentication) { if (authenticationPacket is null) { return(null); } if (!await AuthenticateAsync(socket, authenticationPacket, cancellationToken).ConfigureAwait(false)) { return(null); } } if (!await ConnectAsync(socket, endPoint, cancellationToken).ConfigureAwait(false)) { return(null); } return(Interlocked.Exchange(ref socket, null)); } finally { if (!(socket is null)) { socket.Dispose(); } } }
static async Task Main(string[] args) { try { //await socket.ConnectAsync("127.0.0.1", 5000); await Task.Delay(2000); var conn = await SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 5000)); var encoder = new BasicFrameEncoder(conn.Output); //var producer = conn.Output.AsPipeFrameProducer(new HeaderBasicFrameEncoder()); await encoder.EncodeEnumerableAsync(ProduceFrames()); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadLine(); Console.ReadLine(); }
public async Task CanCreateWorkingEchoServer_ChannelSocketServer_ChannelSocketClient() { var endpoint = new IPEndPoint(IPAddress.Loopback, 5010); const string MessageToSend = "Hello world!"; string reply = null; using (var server = new SocketListener()) { server.OnConnection(Echo); server.Start(endpoint); using (var client = await SocketConnection.ConnectAsync(endpoint)) { var output = client.Output.Alloc(); output.WriteUtf8String(MessageToSend); await output.FlushAsync(); client.Output.Complete(); while (true) { var input = await client.Input.ReadAsync(); // wait for the end of the data before processing anything if (client.Input.Reading.IsCompleted) { reply = input.GetUtf8String(); client.Input.Advance(input.End); break; } else { client.Input.Advance(input.Start, input.End); } } } } Assert.Equal(MessageToSend, reply); }
public async Task <Client> ConnectAsync(string host, int port) { lock (_syncObj) { if (!_finish) { throw new Exception($"`{nameof(ConnectAsync)}` should be used after `{nameof(Finish)}`"); } } IPAddress[] addresses = await Dns.GetHostAddressesAsync(host); foreach (IPAddress address in addresses) { IPEndPoint endpoint = new IPEndPoint(address, port); SocketConnection conn = await SocketConnection.ConnectAsync(endpoint); return(new Client(this, _loggerFactory, conn, _protocol.NewCodec())); } throw new Exception($"GetHostAddress failed: {host}"); }
static async Task Main(string[] args) { var endpoint = new IPEndPoint(IPAddress.Loopback, 5020); while (true) { Console.Out.WriteLine("Enter in your message to echo..."); var message = Console.In.ReadLine(); using (var client = await SocketConnection.ConnectAsync(endpoint)) { var output = client.Output.Alloc(); output.Append(message, SymbolTable.InvariantUtf8); await output.FlushAsync(); client.Output.Complete(); while (true) { var result = await client.Input.ReadAsync(); var input = result.Buffer; if (result.IsCompleted) { Console.Out.WriteLine(input.GetUtf8String()); client.Input.Advance(input.End); break; } else { client.Input.Advance(input.Start, input.End); } } } } }
public static async Task <WebSocketConnection> ConnectAsync( string location, string protocol = null, string origin = null, Action <HttpRequestHeaders> addHeaders = null, ChannelFactory channelFactory = null) { WebSocketServer.WriteStatus(ConnectionType.Client, $"Connecting to {location}..."); Uri uri; if (!Uri.TryCreate(location, UriKind.Absolute, out uri) || uri.Scheme != "ws") { throw new ArgumentException(nameof(location)); } IPAddress ip; if (!IPAddress.TryParse(uri.Host, out ip)) { throw new NotImplementedException("host must be an IP address at the moment, sorry"); } WebSocketServer.WriteStatus(ConnectionType.Client, $"Opening socket to {ip}:{uri.Port}..."); var socket = await SocketConnection.ConnectAsync(new IPEndPoint(ip, uri.Port), channelFactory); return(await WebSocketProtocol.ClientHandshake(socket, uri, origin, protocol)); }
static async Task Main(string[] args) { try { //await socket.ConnectAsync("127.0.0.1", 5000); await Task.Delay(4000); var address = Environment.GetEnvironmentVariable("BENCH_IP") ?? "127.0.0.1"; Console.WriteLine(address); var conn = await SocketConnection.ConnectAsync(new IPEndPoint(IPAddress.Parse(address), 5000)); var encoder = new BasicFrameEncoder(); encoder.Reset(conn.Output); //var producer = conn.Output.AsPipeFrameProducer(new HeaderBasicFrameEncoder()); await encoder.EncodeAsyncEnumerableAsync(ProduceFrames()); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadLine(); Console.ReadLine(); }
public void Start() { _client = SocketConnection.ConnectAsync(endpoint).Result; Task.Run(() => ReadMessages(_client)); }
static async Task Main() { using var server = new EchoServer(Port); await Task.Yield(); SocketConnection.AssertDependencies(); Log("Connecting..."); using var connection = await SocketConnection.ConnectAsync(new IPEndPoint (IPAddress.Loopback, Port)); Log("Connected"); Guid guid = Guid.NewGuid(); Log($"Writing '{guid}'..."); var output = connection.Output; var memory = output.GetMemory(30); if (!Utf8Formatter.TryFormat(guid, memory.Span, out var bytes)) { throw new FormatException(); } output.Advance(bytes); //Log($"Flushing..."); //var flushResult = await output.FlushAsync(); //Log($"IsCompleted:{flushResult.IsCompleted}, IsCanceled:{flushResult.IsCanceled}"); //Log($"Reading..."); //var input = connection.Input; //while (true) //{ // Log($"Reading..."); // var readResult = await input.ReadAsync(); // Log($"IsCompleted:{readResult.IsCompleted}, IsCanceled:{readResult.IsCanceled}, Length:{readResult.Buffer.Length}"); // if (readResult.IsCompleted || readResult.IsCanceled) break; // if (readResult.Buffer.Length >= 36) // { // var buffer = readResult.Buffer; // var len = checked((int)buffer.Length); // var arr = ArrayPool<byte>.Shared.Rent(len); // try // { // buffer.CopyTo(arr); // var s = Encoding.UTF8.GetString(arr, 0, len); // Log($"Received: '{s}'"); // } // finally // { // ArrayPool<byte>.Shared.Return(arr); // } // input.AdvanceTo(readResult.Buffer.End); // break; // } // else // { // input.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End); // } //} //Log($"Closing output..."); //output.Complete(); }
public async Task Connect(EndPoint destination, IDuplexPipe client, IDuplexPipe server) { var sc = await SocketConnection.ConnectAsync(destination); await DuplexPipe.CopyDuplexPipe(client, sc); }