public void send_text(string src, out int length) { client.ConnectAsync(address_con_to, port[0]); byte[] bytes = (new System.Text.UTF8Encoding()).GetBytes(src); length = bytes.Length; foreach (byte a in bytes) { client.WriteStream.WriteByte(a); client.WriteStream.FlushAsync(); Task.Delay(50); } client.DisconnectAsync(); }
public Task TcpSocketClient_ShouldThrowNormalException_WhenNotPlatformSpecific() { var sut = new TcpSocketClient(); var tooHighForAPort = Int32.MaxValue; return(Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => sut.ConnectAsync("127.0.0.1", tooHighForAPort))); }
public Task TcpSocketClient_ShouldThrowPCLException_InPlaceOfNativeSocketException() { var sut = new TcpSocketClient(); var unreachableHostName = ":/totallynotvalid@#$"; return(Assert.ThrowsAsync <Exception>(() => sut.ConnectAsync(unreachableHostName, 8000))); }
public async Task ShouldThrowExceptionIfConnectionTimedOut() { var client = new TcpSocketClient(new SocketSettings { ConnectionTimeout = TimeSpan.FromSeconds(1), HostResolver = new SystemHostResolver(), EncryptionManager = new EncryptionManager(false, null) }); // ReSharper disable once PossibleNullReferenceException // use non-routable IP address to mimic a connect timeout // https://stackoverflow.com/questions/100841/artificially-create-a-connection-timeout-error var exception = await Record.ExceptionAsync( () => client.ConnectAsync(new Uri("bolt://192.168.0.0:9998"))); exception.Should().NotBeNull(); exception.Should().BeOfType <IOException>(); exception.Message.Should().Be( "Failed to connect to server 'bolt://192.168.0.0:9998/' via IP addresses'[192.168.0.0]' at port '9998'."); var baseException = exception.GetBaseException(); baseException.Should().BeOfType <OperationCanceledException>(exception.ToString()); baseException.Message.Should().Be("Failed to connect to server 192.168.0.0:9998 within 1000ms."); }
async void SocketButton_Clicked(object sender, EventArgs e) { var address = "10.0.2.2"; var port = 2001; var sendString = $"{Name.Text}," + $"{Product.Text}," + $"{Lot.Text}," + $"{Date.Date.ToString("yyyy/MM/dd")} {Time.Time}\n"; using (var client = new TcpSocketClient()) { try { await client.ConnectAsync(address, port); var enc = Encoding.UTF8; var sendBytes = enc.GetBytes(sendString); foreach (var byteData in sendBytes) { client.WriteStream.WriteByte(byteData); await client.WriteStream.FlushAsync(); } await client.DisconnectAsync(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.InnerException); } } }
public async void ReceiveAsync_Test() { // Arrange var stream = new MemoryStream(100); tcpClientMock.Setup(s => s.Connected).Returns(true); tcpClientMock.Setup(s => s.GetStream).Returns(stream); var socketClient = new TcpSocketClient <Message, Message>(tcpClient, logger); string host = ""; int port = 0; var token = CancellationToken.None; await socketClient.ConnectAsync(host, port, token); var sentMessage = new Message(MessageID.Unknown, 1, new EmptyAnswerPayload()); await socketClient.SendAsync(sentMessage, token); stream.Seek(0, SeekOrigin.Begin); // Act (bool wasReceived, Message message) = await socketClient.ReceiveAsync(token); // Assert Assert.True(wasReceived, "Should receive message"); Assert.True(message.AreAllPropertiesTheSame(sentMessage), "Received message should be the same as sent"); }
public static bool Connect() { if (ImageComparisonServer != null) { return(true); } try { ImageComparisonServer = new TcpSocketClient(); var t = Task.Run(async() => await ImageComparisonServer.ConnectAsync(XenkoImageServerHost, XenkoImageServerPort)); t.Wait(); // Send initial parameters var networkStream = ImageComparisonServer.WriteStream; var binaryWriter = new BinaryWriter(networkStream); ImageTestResultConnection.Write(binaryWriter); return(true); } catch (Exception) { ImageComparisonServer = null; return(false); } }
public async Task Run() { await _client.ConnectAsync("13.81.65.60", 4088); _console.WriteLine("client is connected"); try { var buffer = new byte[BufferSize]; var offset = 0; var actuallyRead = 0; do { actuallyRead = await _client.GetStream().ReadAsync(buffer, 0, BufferSize); offset += actuallyRead; _console.WriteLine(offset.ToString()); } while (actuallyRead != 0); //_track.Stop(); _console.WriteLine("Completed"); } catch (Exception exception) { _console.WriteLine(exception.Message); throw; } }
private Task OnlyThrowsSocketExceptionOnWinRT() { var sut = new TcpSocketClient(); var tooHighForAPort = Int32.MaxValue; return(sut.ConnectAsync("127.0.0.1", tooHighForAPort)); }
private async void TcpServer() { // Send Message Via TCP var address = "255.255.255.255"; var port = 25000; var r = new Random(); var client = new TcpSocketClient(); await client.ConnectAsync(address, port); Debug.WriteLine("we're connected!"); var msg = $"DeviceState: {_product.State} DeviceLevel: {_product.level}"; byte[] toBytes = Encoding.ASCII.GetBytes(msg); // we're connected! try { for (int i = 0; i < toBytes.Length; i++) { // write to the 'WriteStream' property of the socket client to send data client.WriteStream.WriteByte(toBytes[i]); await client.WriteStream.FlushAsync(); // wait a little before sending the next bit of data //await Task.Delay(TimeSpan.FromMilliseconds(500)); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } await client.DisconnectAsync(); }
private Task OnlyThrowsSocketExceptionOnNet() { var sut = new TcpSocketClient(); var unreachableHostName = ":/totallynotvalid@#$"; return(sut.ConnectAsync(unreachableHostName, 8000)); }
protected override async void AddedToScene() { base.AddedToScene(); // Use the bounds to layout the positioning of our drawable assets var bounds = VisibleBoundsWorldspace; spriteUp1.PositionX = bounds.Center.X - spriteUp1.ContentSize.Width; spriteUp1.PositionY = 4 * bounds.Center.Y / 3; spriteUp2.PositionX = bounds.Center.X + spriteUp2.ContentSize.Width; spriteUp2.PositionY = 4 * bounds.Center.Y / 3; spriteDown1.PositionX = bounds.Center.X - spriteDown1.ContentSize.Width; spriteDown1.PositionY = 2 * bounds.Center.Y / 3; spriteDown2.PositionX = bounds.Center.X + spriteDown2.ContentSize.Width; spriteDown2.PositionY = 2 * bounds.Center.Y / 3; client = new TcpSocketClient(); try { await client.ConnectAsync(App.IPAddress, 51717); } catch { } }
public async Task StartClient(string address, int port) { // Create TCP client var socket = new TcpSocketClient(2048); try { await socket.ConnectAsync(address, port); SetSocket(socket); //socket.NoDelay = true; // Do an ack with magic packet (necessary so that we know it's not a dead connection, // it sometimes happen when doing port forwarding because service don't refuse connection right away but only fails when sending data) await SendAndReceiveAck(socket, MagicAck, MagicAck); if (Connected != null) { Connected(this); } isConnected = true; } catch (Exception) { DisposeSocket(); throw; } }
/// <summary> /// Listen at the current socket and interpret the received commands. /// </summary> private static async void Listen() { try { await tcpSocketClient.ConnectAsync(identification.Address, identification.Port); } catch (Exception e) { throw new Exception(301, "The connection could not established"); } if (tcpSocketClient != null) { connected = true; //Send a connection command to transfer the current device var command = new ConnectionCommand(CommandType.Connection.ToString(), ConnectionCommandType.Connect.ToString(), identification, Device); SendCmd(command.ToJsonString()); //Receive the packages and put them to the parser while (connected) { Interpreter.Parse(ReceiveCmd()); } return; } throw new Exception(302, "The created socket doesn't exist"); }
private async void ConnectButtonOnClick(object sender, EventArgs eventArgs) { _client = new TcpSocketClient(); await _client.ConnectAsync("192.168.1.3", 4088); _connectionStatus.Text = "Connected"; _track.Play(); try { var buffer = new byte[BufferSize]; var offset = 0; var actuallyRead = 0; do { actuallyRead = await _client.Socket.GetStream().ReadAsync(buffer, 0, BufferSize); offset += actuallyRead; _message.Text = offset.ToString(); _track.Write(buffer, 0, actuallyRead); } while (actuallyRead != 0); //_track.Stop(); _message.Text = "Completed"; } catch (Exception exception) { _message.Text = exception.Message; throw; } }
/// <summary> /// Verifies that we are currectly connected to the server. If not but we *wish* to be connected, /// it attempts to establish the connection. If not and we don't wish to be connected, it fails. /// </summary> private async Task EnsureConnectedAsync() { if (_client != null) { // We are likely to still be connected. return; } if (!_shouldBeConnected) { throw new Exception("A method was called that requires an IGS connection but the 'Connect()' method was not called; or maybe 'Disconnect()' was called."); } _client = new TcpSocketClient(); try { await _client.ConnectAsync(_hostname, _port); _streamWriter = new StreamWriter(_client.WriteStream); _streamReader = new StreamReader(_client.ReadStream); _streamWriter.AutoFlush = true; #pragma warning disable 4014 HandleIncomingData(_streamReader).ContinueWith(t => { throw new Exception("If this is connection error, then fine, otherwise throw up."); }, TaskContinuationOptions.OnlyOnFaulted); #pragma warning restore 4014 _composure = IgsComposure.InitialHandshake; _streamWriter.WriteLine("guest"); _streamWriter.WriteLine("toggle client on"); await WaitUntilComposureChangesAsync(); } catch { throw new Exception("We failed to establish a connection with the server."); } }
public async Task Initialize(string host, string port, ConnectionChannel connectionChannel, HeartbeatChannel heartbeatChannel, Action <Stream, bool, CancellationToken> packetReader, CancellationToken cancellationToken) { if (_client == null) { _client = new TcpSocketClient(); } await _client.ConnectAsync(host, int.Parse(port), true, cancellationToken, true); await connectionChannel.OpenConnection(); heartbeatChannel.StartHeartbeat(); await Task.Run(async() => { while (true) { var sizeBuffer = new byte[4]; // First message should contain the size of message await _client.ReadStream.ReadAsync(sizeBuffer, 0, sizeBuffer.Length, cancellationToken); // The message is little-endian (that is, little end first), // reverse the byte array. Array.Reverse(sizeBuffer); //Retrieve the size of message var messageSize = BitConverter.ToInt32(sizeBuffer, 0); var messageBuffer = new byte[messageSize]; await _client.ReadStream.ReadAsync(messageBuffer, 0, messageBuffer.Length, cancellationToken); var answer = new MemoryStream(messageBuffer.Length); await answer.WriteAsync(messageBuffer, 0, messageBuffer.Length, cancellationToken); answer.Position = 0; packetReader(answer, true, cancellationToken); } }, cancellationToken); }
public async void StartTCP(Device d) { tcpClient = new TcpSocketClient(); try { await tcpClient.ConnectAsync(d.IPAddress.ToString(), 4210); } catch { return; } Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { mainPage.UpdateView(); }); keepAliveWatch.Start(); timer = new Timer(SendKeepAlive, null, 0, keepAliveTimer); bindedDevice = d; bindedDevice.BindActive = true; isTcpThreadActive = true; tcpReceive = new Thread(TcpReceive); tcpReceive.Start(); }
public async Task Send(string ip, int port) { var r = new Random(); RaiseInfoEvent(string.Format("Connecting to: {0}:{1}", ip, port)); _outChannel = new TcpSocketClient(); RaiseOutChannelStarted(true); await _outChannel.ConnectAsync(ip, port); RaiseInfoEvent("We're connected!"); for (int i = 0; i < 5; i++) { // write to the 'WriteStream' property of the socket client to send data var nextByte = (byte)r.Next(0, 254); RaiseInfoEvent(string.Format("Sending: {0}", nextByte)); _outChannel.WriteStream.WriteByte(nextByte); await _outChannel.WriteStream.FlushAsync(); // wait a little before sending the next bit of data await Task.Delay(TimeSpan.FromMilliseconds(500)); } await _outChannel.DisconnectAsync(); RaiseInfoEvent("Message sent!"); RaiseOutChannelStarted(false); IsSending = false; }
public async Task StartAsync() { client = new TcpSocketClient(); await client.ConnectAsync(address, port); backgroundTask(); this.SomethingHappened?.Invoke(this, "Connection successful..."); }
async public void getConnectionAsync() { address = "192.168.4.1"; //address = "192.168.121.137"; port = 8888; client = new TcpSocketClient(); await client.ConnectAsync(address, port); }
/// <summary> /// Starts the local HTTP server and listen for requests /// </summary> /// <returns>Task completion object</returns> /// <exception cref="InvalidOperationException"> /// If failed to find an unused port or prohibited from listening for new /// connections. /// </exception> public virtual async Task RunServerAsync() { if (Server != null) return; const ushort validPortsMin = 1025; const ushort validPortsMax = ushort.MaxValue; var invalidPorts = new List<ushort>(); var random = new Random(); while (invalidPorts.Count < validPortsMax - validPortsMin) { PortNumber = (ushort) random.Next(validPortsMin, validPortsMax); if (invalidPorts.Contains(PortNumber)) continue; try { Server = new HttpListener(TimeSpan.FromSeconds(30)); await Server.StartTcpRequestListener(PortNumber); Server.HttpRequestObservable.Subscribe(OnHttpRequest); using (var testSocket = new TcpSocketClient()) { var tokenSource = new CancellationTokenSource(); var connectOperation = testSocket.ConnectAsync("127.0.0.1", PortNumber.ToString(), false, tokenSource.Token); tokenSource.CancelAfter(TimeSpan.FromSeconds(10)); await connectOperation; if (connectOperation.IsFaulted || connectOperation.IsCanceled) { if (connectOperation.Exception != null) throw connectOperation.Exception; throw new InvalidOperationException(); } testSocket.Disconnect(); } Protocol = @"http://127.0.0.1:" + PortNumber; } catch (NotImplementedException) { Server = null; throw; } catch { invalidPorts.Add(PortNumber); try { Server?.StopTcpRequestListener(); } catch { // ignored } Server = null; continue; } return; } throw new InvalidOperationException(@"There is no free port to bind to on this machine."); }
public Task TcpSocketClient_Connect_ShouldCancelByCancellationToken() { var sut = new TcpSocketClient(); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var ct = cts.Token; // let's just hope no one's home :) return(Assert.ThrowsAsync <OperationCanceledException>(() => sut.ConnectAsync("99.99.99.99", 51234, cancellationToken: cts.Token))); }
public async Task <IObservable <string> > CreateObservableMessageReceiver( Uri uri, string origin = null, IDictionary <string, string> headers = null, IEnumerable <string> subProtocols = null, bool ignoreServerCertificateErrors = false, TlsProtocolVersion tlsProtocolType = TlsProtocolVersion.Tls12, bool excludeZeroApplicationDataInPong = false) { _websocketListener.ExcludeZeroApplicationDataInPong = excludeZeroApplicationDataInPong; _subjectConnectionStatus.OnNext(ConnectionStatus.Connecting); _innerCancellationTokenSource = new CancellationTokenSource(); ITcpSocketClient socketClient = new TcpSocketClient(); await socketClient.ConnectAsync( uri.Host, uri.Port.ToString(), IsSecureWebsocket(uri), _innerCancellationTokenSource.Token, ignoreServerCertificateErrors, tlsProtocolType); await _webSocketConnectService.ConnectServer( uri, IsSecureWebsocket(uri), socketClient, origin, headers, subProtocols); var observer = Observable.Create <string>( obs => { var disp = _websocketListener.CreateObservableListener( _innerCancellationTokenSource, socketClient) .Subscribe( str => obs.OnNext(str), ex => { WaitForServerToCloseConnectionAsync().Wait(); throw ex; }, () => { WaitForServerToCloseConnectionAsync().Wait(); obs.OnCompleted(); }); return(disp); }); return(observer); }
protected async Task SendOnTcp(string address, int port, byte[] data) { using (var tcpClient = new TcpSocketClient()) { await tcpClient.ConnectAsync(address, port.ToString()); await tcpClient.WriteStream.WriteAsync(data, 0, data.Length); await tcpClient.WriteStream.FlushAsync(); } }
public async Task ConnectAsync(string address, int port, CancellationToken cancellationToken) { try { await _client.ConnectAsync(address, port, IsSecure); } catch (Exception se) { throw new WebException(string.Format("Failed to connect to '{0}:{1}'", address, port), se); } }
private async void StartTest() { var tcpClient = new TcpSocketClient(); await tcpClient.ConnectAsync( "echo.websocket.org", "443", true, CancellationToken.None, ignoreServerCertificateErrors : true, tlsProtocolVersion : TlsProtocolVersion.Tls10); }
public async Task <bool> connect() { try { await socket.ConnectAsync(ip, port); } catch (Exception) { return(false); } return(true); }
private void Init() { try { mSocket.ConnectAsync(SERVER_ADDRESS, SERVER_PORT); } catch (Exception ex) { mSocket.DisconnectAsync(); } // we're connected! }
private static async void StartTcpClient() { var tcpClient = new TcpSocketClient(); await tcpClient.ConnectAsync("www.abc.dk", "8088", secure : true, ignoreServerCertificateErrors : true); var helloWorld = "Hello World!"; var bytes = Encoding.UTF8.GetBytes(helloWorld); await tcpClient.WriteStream.WriteAsync(bytes, 0, bytes.Length); tcpClient.Disconnect(); tcpClient.Dispose(); }
void OnConnectCommandExecuted() { client = new TcpSocketClient(IPAddress.Parse(ServerIpAddress)); client.Received += new TcpSocketClient.ReceiveHandler(client_Received); client.ConnectAsync(UserName, () => { IsChatViewVisible = true; }, error => { MessageBox.Show(error); } ); }