public ConnectAsync ( HostName hostName, string remoteServiceName, SocketProtectionLevel protectionLevel ) : |
||
hostName | HostName | |
remoteServiceName | string | |
protectionLevel | SocketProtectionLevel | |
return |
private async void ConnectUWP() { try { if (exchangeTask != null) { CloseSocket(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); RestartExchange(); connected = true; } catch (Exception e) { Debug.Log("ERROR WHILE TRYING TO CONNECT: " + e.ToString()); } }
public async void ConnectTo(Slide slide) { var duration = slide.AppearanceDuration; var content = slide.Content as ScreenCapture; var ipAddress = content.IPTargetAgent; HostName localHost = null; foreach (var hostName in NetworkInformation.GetHostNames()) { if(hostName.IPInformation != null) { if(hostName.Type == Windows.Networking.HostNameType.Ipv4) { localHost = hostName; } } } var TCPClient = new StreamSocket(); try { var cts = new CancellationTokenSource(); cts.CancelAfter(500); var connectAsync = TCPClient.ConnectAsync( new Windows.Networking.EndpointPair(localHost, "54321", new Windows.Networking.HostName(ipAddress), "54321")); var connectTask = connectAsync.AsTask(cts.Token); await connectTask; this.SendToAgent(slide, TCPClient); } catch(Exception ex) { TCPClient.Dispose(); Debug.WriteLine(ex.Message); this.FireOnConnectionFailed(); return; } }
private async Task<string> DoCommand(string command) { StringBuilder strBuilder = new StringBuilder(); using (StreamSocket clientSocket = new StreamSocket()) { await clientSocket.ConnectAsync(new HostName("192.168.9.108"), "9001"); using (DataWriter writer = new DataWriter(clientSocket.OutputStream)) { writer.WriteString(command); await writer.StoreAsync(); writer.DetachStream(); } using (DataReader reader = new DataReader(clientSocket.InputStream)) { reader.InputStreamOptions = InputStreamOptions.Partial; await reader.LoadAsync(8192); while (reader.UnconsumedBufferLength > 0) { strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength)); await reader.LoadAsync(8192); } reader.DetachStream(); } } return (strBuilder.ToString()); }
/// <summary> /// Attempt to create a tcp connection to a certain host /// </summary> /// <param name="remoteAddress">Address of the remote host</param> /// <param name="connectionTimeout">Time (in milliseconds) that defines how long we should attempt to connect to the other party</param> /// <returns>Returns a StreamSocket to the remote host</returns> private async Task<StreamSocket> Connect(string remoteAddress, int connectionTimeout) { StreamSocket streamSocket = new StreamSocket(); // Make sure a timeout occurs (otherwise it will try to connect forever) CancellationTokenSource cts = new CancellationTokenSource(); try { cts.CancelAfter(connectionTimeout); // Try to connect to the remote address await streamSocket.ConnectAsync(new HostName(remoteAddress), this.port).AsTask(cts.Token); return streamSocket; } catch (TaskCanceledException ex) { // TaskCanceledException will be thrown when the timeout has passed. // Now throw our own exception throw new ConnectionTimedOutException("Could not create connection with host " + remoteAddress + " within the given time-out period of " + connectionTimeout + "ms. "); } catch (System.Exception ex) { // Catch any other exception too System.Diagnostics.Debug.WriteLine("Exception occured in TCPSocketClient.Connect: " + ex); throw; } }
public static void Connect(string address, string port) { if (!connected) { clientSocket = new StreamSocket(); try { serverHost = new HostName(address); serverPort = port; serverHostnameString = address; writer = new DataWriter(clientSocket.OutputStream); clientSocket.ConnectAsync(serverHost, serverPort); connected = true; } catch (Exception) { clientSocket.Dispose(); clientSocket = null; throw new ConnectionErrorException(); } } else { clientSocket.Dispose(); clientSocket = null; connected = false; GamepadClient.Connect(address, port); } }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR StatusTextManager.GetComponent <TextMesh>().text = "UWP TCP client used in Unity!"; #else try { if (exchangeTask != null) { StopExchange(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); RestartExchange(); StatusTextManager.GetComponent <TextMesh>().text = "Connected!"; } catch (Exception e) { errorStatus = e.ToString(); } #endif }
public ConnectionStatus ConnectToSignalingServer(ConnectionOwner connectionOwner) { try { SignaledPeerData.Reset(); SignalingStatus.Reset(); SignaledRelayMessages.Reset(); var socket = new StreamSocket(); socket.EnableTransferOwnership(Guid.Parse(connectionOwner.OwnerId), SocketActivityConnectedStandbyAction.Wake); socket.ConnectAsync(new HostName(SignalingSettings.SignalingServerHost), SignalingSettings.SignalingServerPort, SocketProtectionLevel.PlainSocket) .AsTask() .Wait(); socket.TransferOwnership(SignalingSocketOperation.SignalingSocketId); return new ConnectionStatus { IsConnected = true }; } catch (Exception exception) { return new ConnectionStatus { IsConnected = false }; } }
private async void TryConnect ( ) { if ( connectList.SelectedItem != null ) { try { PeerFinder.Start( ); PeerFinder.AlternateIdentities[ "Bluetooth:Paired" ] = ""; var pairedDevices = await PeerFinder.FindAllPeersAsync(); UpdateStatus( "Connecting to selected device: " + pairedDevices[ connectList.SelectedIndex ].DisplayName ); socket = new StreamSocket(); // Create socket. await socket.ConnectAsync( pairedDevices[ connectList.SelectedIndex ].HostName, "1" ); // Connect to device using socket. connected = true; textblockDevice.Text = "Connected to " + pairedDevices[ connectList.SelectedIndex ].DisplayName; UpdateStatus( "success!" ); WaitForData( socket ); Write( "#p" ); // First ping to test connection. } catch ( Exception ex ) { UpdateStatus( "Error: " + ex.Message + "," + ex.StackTrace ); } } else { UpdateStatus( "Please select a device." ); } }
public TcpTextWriter(string hostName, int port) { if (hostName == null) throw new ArgumentNullException(nameof(hostName)); if ((port < 0) || (port > ushort.MaxValue)) throw new ArgumentException("port"); HostName = hostName; Port = port; #if __IOS__ || MAC UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; #endif try { #if __IOS__ || MAC || ANDROID var client = new TcpClient(hostName, port); writer = new StreamWriter(client.GetStream()); #elif WINDOWS_PHONE || NETFX_CORE var socket = new StreamSocket(); socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture)) .AsTask() .ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite())); #endif } catch { #if __IOS__ || MAC UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; #endif throw; } }
internal async Task ConnectAsync( HostName hostName, string serviceName, string user, string password) { if (controlStreamSocket != null) { throw new InvalidOperationException("Control connection already started."); } this.hostName = hostName; controlStreamSocket = new StreamSocket(); await controlStreamSocket.ConnectAsync(hostName, serviceName); reader = new DataReader(controlStreamSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; writer = new DataWriter(controlStreamSocket.OutputStream); readCommands = new List<string>(); loadCompleteEvent = new AutoResetEvent(false); readTask = InfiniteReadAsync(); FtpResponse response; response = await GetResponseAsync(); VerifyResponse(response, 220); response = await UserAsync(user); VerifyResponse(response, 331); response = await PassAsync(password); VerifyResponse(response, 230); }
public async Task<bool> ConnectAsync(string host, int port, int timeOut = 5000) { try { socket = new StreamSocket(); socket.Control.KeepAlive = true; var cts = new CancellationTokenSource(); cts.CancelAfter(timeOut); await socket.ConnectAsync(new HostName(host), port.ToString()).AsTask(cts.Token); ReceiveAsync(); return true; } catch (TaskCanceledException) { } catch (Exception ex) { //if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) // throw; } Disconnect(); return false; }
/// <summary> /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false. /// You can use it to check remote calls though. /// </summary> /// <param name="host"></param> /// <param name="msTimeout"></param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; try { var serverHost = new HostName(host); using(var client = new StreamSocket()) { await client.ConnectAsync(serverHost, "http"); return true; } } catch(Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }
public async void SendMessage(string message) { Windows.Networking.Sockets.StreamSocket streamSocket = null; streamSocket = new Windows.Networking.Sockets.StreamSocket(); try { Debug.Log("Trying to connect"); await streamSocket.ConnectAsync(HostAddress, "1337"); Debug.Log("Connected!"); Stream streamOut = streamSocket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(streamOut); await writer.WriteLineAsync(message); Debug.Log("The following message was sent: " + message); await writer.FlushAsync(); //creat input stream and read it into a string (for responses from RPI3) /*Stream streamIn = streamSocket.InputStream.AsStreamForRead(); * StreamReader reader = new StreamReader(streamIn); * string response = await reader.ReadLineAsync();*/ } catch (Exception e) { //catch an error messages and display Debug.Log(e.Message); } finally { //end by disposing the socket and clearing the resources streamSocket.Dispose(); } }
private async void Button_Click(object sender, RoutedEventArgs e) { try { ////Create the StreamSocket and establish a connection to the echo server. //Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket(); //The server hostname that we will be establishing a connection to. We will be running the server and client locally, //so we will use localhost as the hostname. Windows.Networking.HostName serverHost = new Windows.Networking.HostName("133.37.56.223"); //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc. //For the echo server/client application we will use a random port 1337. string serverPort = "50005"; await socket.ConnectAsync(serverHost, serverPort); while (true) { //Read data from the echo server. Stream streamIn = socket.InputStream.AsStreamForRead(); StreamReader reader = new StreamReader(streamIn); System.Diagnostics.Debug.WriteLine("ok"); string response = await reader.ReadLineAsync(); //サーバからの入力待ち textblock.Text = response; } } catch (Exception) { //Handle exception here. } }
private async Task ConnectAsyncInternal(HostName hostName) { _tokenSource = new CancellationTokenSource(); _socket = new StreamSocket(); // połącz z kontrolerem na porcie 5555 await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket); // wyslij komendę odblokowującą await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer()); // read the "Accept:EV340\r\n\r\n" response //stworzenie bufor na odpowiedź IBuffer bufferResponse = new Buffer(128); //pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3 await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial); //przekształcenie danych z bufora na ciag znaków w formacie UTF8 string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length); if (string.IsNullOrEmpty(response)) //zgłoszenie błędu w razie braku odpowiedzi throw new Exception("LEGO EV3 brick did not respond to the unlock command."); //rozpoczęcie pobierania danych await ThreadPool.RunAsync(PollInput); }
private void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR errorStatus = "UWP TCP client used in Unity!"; #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); Debug.Log("success connected to" + host); } catch (Exception e) { errorStatus = e.ToString(); Debug.Log("Error could not connect to" + host); isConnected = false; return; } #endif isConnected = true; }
public async Task Connect() { PeerFinder.AlternateIdentities["Bluetooth:SDP"] = ServiceGUID.ToString(); var peers = await PeerFinder.FindAllPeersAsync(); foreach (var p in peers) { var h = p.ServiceName; } // TODO: obviously list these instead of taking the first var peer = peers.FirstOrDefault(); if (peer != null) { var socket = new StreamSocket(); try { // default service name? await socket.ConnectAsync(peer.HostName, ServiceName); var connection = new DuplexConnection(socket); var device = new BluetoothDevice(peer.DisplayName, peer.HostName, peer.ServiceName); if (ConnectionEstablished != null) { ConnectionEstablished(this, new ClientConnectedEventArgs(device, connection)); } } catch (Exception ex) { } } }
/// <summary> /// Attempt a TCP socket connection to the given host over the given port /// </summary> /// <param name="serverAddress">The address of the server</param> /// <param name="portNumber">The port number to connect</param> private bool Connect(string serverAddress, int portNumber) { HostName serverHost = new HostName(serverAddress); mSocket = new StreamSocket(); mSocket.Control.KeepAlive = true; Task connectTask = mSocket.ConnectAsync(serverHost, portNumber.ToString()).AsTask(); try { if(!connectTask.Wait(TIMEOUT)) { // timed out connecting to the server System.Diagnostics.Debug.WriteLine("Timed out connecting to TCP server"); return false; } } catch(AggregateException a) { // exception when running connect task. failed to connect to server System.Diagnostics.Debug.WriteLine("Failed to connect to TCP server. Error: " + a.GetBaseException().Message); return false; } // set up the writer writer = new DataWriter(mSocket.OutputStream); // set up the reader reader = new DataReader(mSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; // Set inputstream options so that we don't have to know the data size // start listening for messages Task.Run(() => StartReceiving()); // start receiving on a new thread Task.Run(() => StartKeepAlive()); // start receiving on a new thread return true; }
public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args) { _socket = new StreamSocket(); var server = new HostName(ipOrHost); // TCP timeouts in WinRT are excessive, shorten them here using task cancellation var cts = new CancellationTokenSource(); try { cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000); _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName)); await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token); _clientUid = args.ClientUid; StartReceiving(); } catch (TaskCanceledException) { args.SocketException = new IOException("Timeout error while trying to connect."); _clientUid = null; _socket.Dispose(); _socket = null; } catch (Exception ex) { args.SocketException = ex; _clientUid = null; _socket.Dispose(); _socket = null; } args.Complete(); }
public async void Initialize() { // Enumerate devices with the object push service var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.ObexObjectPush)); if (services.Count > 0) { // Initialize the target Bluetooth BR device var service = await RfcommDeviceService.FromIdAsync(services[0].Id); // Check that the service meets this App's minimum requirement if (SupportsProtection(service) && IsCompatibleVersion(service)) { _service = service; // Create a socket and connect to the target _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel .BluetoothEncryptionAllowNullAuthentication); // The socket is connected. At this point the App can wait for // the user to take some action, e.g. click a button to send a // file to the device, which could invoke the Picker and then // send the picked file. The transfer itself would use the // Sockets API and not the Rfcomm API, and so is omitted here for // brevity. } } }
public static async Task<bool> CheckServerAddressWP(string url, int port = 80, int msTimeout = 5000) { bool retVal = false; string originalUrl = url; if (!IsUrlValid(url)) return retVal; try { using (var tcpClient = new StreamSocket()) { url = url.Replace("http://", string.Empty).Replace("https://", string.Empty); if (url.Last() == '/') url = url.Substring(0, url.Length - 1); await tcpClient.ConnectAsync(new Windows.Networking.HostName(url), port.ToString(), SocketProtectionLevel.PlainSocket); if (tcpClient.Information.RemoteHostName.ToString().ToLower() == url.ToLower()) retVal = true; tcpClient.Dispose(); } } catch (Exception ex) { retVal = false; } retVal &= await ExposesContosoMomentsWebAPIs(originalUrl); return retVal; }
public async void sendMessage(string message) { Debug.Log("LearningHub.sendMessage 1: IP: " + IPAddress + ", port: " + port + ", message: " + message); #if !UNITY_EDITOR try { // Create the StreamSocket using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName(IPAddress); Debug.Log("LearningHub.sendMessage 2: Host: " + hostName + ", IP: " + IPAddress + ", port: " + port + ", message: " + message); await streamSocket.ConnectAsync(hostName, port); using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(message); await streamWriter.FlushAsync(); } } Debug.Log("LearningHub.sendMessage 3: Host: " + hostName + ", IP: " + IPAddress + ", port: " + port + ", message: " + message); } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); Debug.Log("Learning hub not found"); } #endif Debug.Log("WEKIT LearningHUb: sending message to learning hub"); }
public async void SendMessage(string msg) { HostName hostName; try { hostName = new HostName("localhost"); } catch (ArgumentException) { return; } StreamSocket socket; try { using (socket = new StreamSocket()) { await socket.ConnectAsync(hostName, port2); //CoreApplication.Properties.Add("connected", null); DataWriter dw = new DataWriter(socket.OutputStream); dw.WriteString(msg); await dw.StoreAsync(); } } catch { //break; } }
private async void RefreshLogsTapped(object sender, TappedRoutedEventArgs e) { var btn = sender as Button; if (btn != null) { btn.IsEnabled = false; try { using (var socket = new StreamSocket()) { await socket.ConnectAsync(new HostName(@"127.0.0.1"), @"11111"); var handler = new WinRtTransferHandler(socket); _viewModel.Load(await new LogsClientHandler(2, handler).GetConfigsAsync()); await handler.CloseAsync(); } } catch { } finally { btn.IsEnabled = true; } } }
public static async Task<bool> ConnectAsync() { if (imageComparisonServer != null) return true; try { imageComparisonServer = new StreamSocket(); await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString()); // Send initial parameters using (var memoryStream = new MemoryStream()) { var binaryWriter = new BinaryWriter(memoryStream); ImageTestResultConnection.Write(binaryWriter); var dataWriter = new DataWriter(imageComparisonServer.OutputStream); dataWriter.WriteBytes(memoryStream.ToArray()); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } return true; } catch (Exception) { imageComparisonServer = null; return false; } }
private async void ConnectUWP(string host, string port) { try { if (exchangeTask != null) { StopExchange(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); } catch (Exception e) { e.ToString(); } }
private async Task CaptureReadings() { #region Cheat //var devices = await DeviceInformation.FindAllAsync( // RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort) // ); //var device = devices.Single((x) => x.Name == "RNBT-9A57"); //RfcommDeviceService service = null; //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => //{ // service = RfcommDeviceService.FromIdAsync(device.Id).AsTask().Result; //}); //using (var socket = new StreamSocket()) //{ // await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // var reader = new DataReader(socket.InputStream); // while (true) // { // var distance = await this.ReadDistanceAsync(reader); // await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => // { // this.ReadingTextBlock.Text = distance.ToString(); // }); // } //} #endregion var devices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort) ); var device = devices.Single(x => x.Name == "RNBT-9A57"); RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(device.Id); using (var socket = new StreamSocket()) { await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); var reader = new DataReader(socket.InputStream); while (true) { var distance = await this.ReadDistanceAsync(reader); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.ReadingTextBlock.Text = distance.ToString(); }); } } }
/// <summary> /// Creates the stream the NmeaDevice is working on top off. /// </summary> /// <returns></returns> protected override async Task <System.IO.Stream> OpenStreamAsync() { var socket = new Windows.Networking.Sockets.StreamSocket(); #if WINDOWS_UWP if (m_devicePeer != null) { await socket.ConnectAsync(m_devicePeer.HostName, "1"); } else #endif { await socket.ConnectAsync(m_deviceService.ConnectionHostName, m_deviceService.ConnectionServiceName); } m_socket = socket; return(socket.InputStream.AsStreamForRead()); }
public async Task OpenAsync( string hostName, int port, bool useSsl ) { if ( _socket == null ) { _socket = new StreamSocket( ); if ( useSsl ) await _socket.ConnectAsync( new HostName( hostName ), port.ToString( ), SocketProtectionLevel.Ssl ); else await _socket.ConnectAsync( new HostName( hostName ), port.ToString( ) ); _reader = new DataReader( _socket.InputStream ); _reader.InputStreamOptions = InputStreamOptions.Partial; _writer = new DataWriter( _socket.OutputStream ); } }
public async Task<StreamSocket> Connect(string address, int port) { StreamSocket socket = new StreamSocket(); await socket.ConnectAsync(new HostName(address), port.ToString()); return socket; }
/// <summary> /// Connects the client with a remote host providing telemetry functionality. /// </summary> /// <param name="strRemoteHostName">Name of the Remote Host</param> /// <param name="strConnectionPort">Port, which will be used for the connection</param> public async void Connect(string strRemoteHostName, string strConnectionPort) { m_pTcpSocket = new StreamSocket(); m_pTelemetryWriterSemaphoreSlim = new SemaphoreSlim(0, 1); var endPointPair = new EndpointPair(new HostName("192.168.0.16"), strConnectionPort, new HostName(strRemoteHostName), strConnectionPort); await m_pTcpSocket.ConnectAsync(endPointPair); m_pTelemetryWriter = new DataWriter(m_pTcpSocket.OutputStream); }
public async Task ConnectAsync() { _socket = new StreamSocket(); await _socket.ConnectAsync(new HostName(GlobalConfig.IpAddress), GlobalConfig.Port.ToString()); _dataWriter = new DataWriter(_socket.OutputStream); _dataReader = new DataReader(_socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial }; StartListening(); }
private async void OnForegroundSocketClicked(object sender, RoutedEventArgs e) { socket = new StreamSocket(); HostName host = new HostName("localhost"); try { await socket.ConnectAsync(host, "1983"); isConnected = true; while (isConnected) { try { DataReader reader; using (reader = new DataReader(socket.InputStream)) { // Set the DataReader to only wait for available data (so that we don't have to know the data size) reader.InputStreamOptions = InputStreamOptions.Partial; // The encoding and byte order need to match the settings of the writer we previously used. reader.UnicodeEncoding = UnicodeEncoding.Utf8; reader.ByteOrder = ByteOrder.LittleEndian; // Send the contents of the writer to the backing stream. // Get the size of the buffer that has not been read. await reader.LoadAsync(256); // Keep reading until we consume the complete stream. while (reader.UnconsumedBufferLength > 0) { string readString = reader.ReadString(reader.UnconsumedBufferLength); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { messages.Add(readString); }); Debug.WriteLine(readString); await reader.LoadAsync(256); } reader.DetachStream(); } } catch (Exception exc) { MessageDialog dialog = new MessageDialog("Error reading the data"); await dialog.ShowAsync(); } } } catch (Exception exc) { MessageDialog dialog = new MessageDialog("Error connecting to the socket"); await dialog.ShowAsync(); } }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { StreamSocket ss = new StreamSocket(); await ss.ConnectAsync( new HostName(address.Host), address.Port.ToString(), address.UseSsl ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket); this.socket = ss; }
private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (CoreApplication.Properties.ContainsKey("clientSocket")) { rootPage.NotifyUser("此步骤已完成请下一步", NotifyType.ErrorMessage); return; } if (string.IsNullOrEmpty(ServiceNameForConnect.Text)) { rootPage.NotifyUser("请提供一个服务器名称", NotifyType.ErrorMessage); return; } // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the // text box validating the host name is required since it was received from an untrusted source // (user input). The host name is validated by catching ArgumentExceptions thrown by the HostName // constructor for invalid input. HostName hostName; try { hostName = new HostName(HostNameForConnect.Text); } catch (ArgumentException) { rootPage.NotifyUser("无效的主机名", NotifyType.ErrorMessage); throw; } StreamSocket socket = new StreamSocket(); socket.Control.KeepAlive = false; CoreApplication.Properties.Add("clientSocket", socket); try { if (adapter == null) { rootPage.NotifyUser("连接至:" + HostNameForConnect.Text, NotifyType.StatusMessage); await socket.ConnectAsync(hostName, ServiceNameForConnect.Text); rootPage.NotifyUser("已连接", NotifyType.StatusMessage); } else { rootPage.NotifyUser("连接至:" + HostNameForConnect.Text + "使用网络适配器" + adapter.NetworkAdapterId, NotifyType.StatusMessage); await socket.ConnectAsync(hostName, ServiceNameForConnect.Text, SocketProtectionLevel.PlainSocket, adapter); rootPage.NotifyUser("Connected using network adapter " + adapter.NetworkAdapterId, NotifyType.StatusMessage); } CoreApplication.Properties.Add("connected", null); } catch (Exception exception) { if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public static async Task<bool> IsOnline() { var googleHost = new HostName("google.com"); var socket = new StreamSocket(); try { var cts = new CancellationTokenSource(TimeoutMilliseconds); await socket.ConnectAsync(googleHost, "http").AsTask(cts.Token); return socket.Information.RemoteAddress != null; } catch { return false; } }
/// <summary> /// Creates the protocol - encapsulates the socket creation /// </summary> /// <param name="peer">The peer.</param> /// <returns>A protocol object</returns> public static async Task<Protocol> CreateProtocolAsync(PeerInformation peer) { #if WINDOWS_PHONE // {00001101-0000-1000-8000-00805f9b34fb} specifies we want a Serial Port - see http://developer.nokia.com/Community/Wiki/Bluetooth_Services_for_Windows_Phone StreamSocket socket = new StreamSocket(); await socket.ConnectAsync(peer.HostName, new Guid(0x00001101, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB).ToString("B")); #elif NETFX_CORE StreamSocket socket = await PeerFinder.ConnectAsync(peer); #endif return new Protocol(socket); }
protected override async void Loop() { Streams.DataReader reader = null; try { while (true) { if (socket == null) { socket = new StreamSocket(); await socket.ConnectAsync(new HostName(DroneClient.Host), _ServiceName); } var readBuf = new Streams.Buffer((uint)NetworkBufferSize); var readOp = socket.InputStream.ReadAsync(readBuf, (uint)NetworkBufferSize, Streams.InputStreamOptions.Partial); readOp.Completed = (IAsyncOperationWithProgress<Streams.IBuffer, uint> asyncAction, AsyncStatus asyncStatus) => { switch (asyncStatus) { case AsyncStatus.Completed: Debug.WriteLine("Config:Completed "); try { Streams.IBuffer localBuf = asyncAction.GetResults(); uint bytesRead = localBuf.Length; Debug.WriteLine("Config:Buffer (" + bytesRead + ")"); reader = Streams.DataReader.FromBuffer(localBuf); OnDataReadCompletion(bytesRead, reader); } catch (Exception e) { Debug.WriteLine(e.ToString()); } break; case AsyncStatus.Canceled: Debug.WriteLine("Config:Canceled "); break; case AsyncStatus.Error: Debug.WriteLine("Config:Error "); break; } }; //socket.Dispose(); await Task.Delay(500); } } catch (Exception e) { Debug.WriteLine(e.ToString()); Stop(); } }
internal async Task ConnectAsync(Uri url) { underlayingSocket = new StreamSocket(); await underlayingSocket.ConnectAsync(remoteHostName: new Windows.Networking.HostName(url.Host), remoteServiceName: url.Port.ToString()); await SendHeaders(url); await SetStream(); //underlayingClient.DefaultRequestHeaders.Add("icy-metadata", "1"); //underlayingClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"); //await SetStream(url); }
/// <summary> /// Creates the stream the GrblDevice is working on top off. /// </summary> /// <returns></returns> protected override async Task <System.IO.Stream> OpenStreamAsync() { var socket = new Windows.Networking.Sockets.StreamSocket(); await socket.ConnectAsync( #if NETFX_CORE m_device.ConnectionHostName, m_device.ConnectionServiceName); #else m_device.HostName, "1"); #endif m_socket = socket; return(socket.InputStream.AsStreamForRead()); }
private async void StartClient() { try { // Create the StreamSocket and establish a connection to the echo server. using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName("localhost"); this.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, StreamSocketAndListenerPage.PortNumber); this.clientListBox.Items.Add("client connected"); // Send a request to the echo server. string request = "Hello, World!"; using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(request); await streamWriter.FlushAsync(); } } this.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request)); // Read data from the echo server. string response; using (Stream inputStream = streamSocket.InputStream.AsStreamForRead()) { using (StreamReader streamReader = new StreamReader(inputStream)) { response = await streamReader.ReadLineAsync(); } } this.clientListBox.Items.Add(string.Format("client received the response: \"{0}\" ", response)); } this.clientListBox.Items.Add("client closed its socket"); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
public async Task <string> sendMessage(string message, bool awaitResponse) { Debug.Log("sending message to learning hub: " + message); string responseMessage = ""; #if !UNITY_EDITOR try { // Create the StreamSocket using (Windows.Networking.Sockets.StreamSocket streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName(IPAddress); await streamSocket.ConnectAsync(hostName, port); using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (StreamWriter streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(message); await streamWriter.FlushAsync(); } } if (awaitResponse) { using (Stream inputStream = streamSocket.InputStream.AsStreamForRead()) { using (StreamReader streamReader = new StreamReader(inputStream)) { responseMessage = streamReader.ReadToEnd(); } } } } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); } #endif Debug.Log("sent message to learning hub: " + message); if (awaitResponse) { Debug.Log("received response from learning hub: " + responseMessage); } return(responseMessage); }
async Task ConnectAsync(string host, string port) { try { #if !UNITY_EDITOR ClientSocket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await ClientSocket.ConnectAsync(serverHost, port); #endif } catch (Exception e) { client.NotifyMainThread(0, e.ToString(), 0); } }
private async void Button_Click_1(object sender, RoutedEventArgs e) { Windows.Networking.Sockets.StreamSocket streamSocket = new Windows.Networking.Sockets.StreamSocket(); HostName localHost = new HostName("localhost"); HostName remoteHost = new HostName("www.andrea-allievi.com"); EndpointPair ep = new EndpointPair(localHost, "", remoteHost, "80"); MessageDialog dlg = new Windows.UI.Popups.MessageDialog(""); // Save the socket, so subsequent steps can use it. Windows.ApplicationModel.Core.CoreApplication.Properties.Add("clientSocket", streamSocket); try { await streamSocket.ConnectAsync(remoteHost, "80"); } catch (Exception exc) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exc.HResult) == SocketErrorStatus.Unknown) { throw; } dlg.Title = "Socket Error!"; dlg.Content = "Connect failed with error: " + exc.Message; dlg.ShowAsync(); return; } DataWriter writer = new DataWriter(streamSocket.OutputStream); writer.WriteString("GET /index.html\r\n"); await writer.StoreAsync(); DataReader reader = new DataReader(streamSocket.InputStream); uint len = 2048; reader.InputStreamOptions = InputStreamOptions.Partial; uint numStrBytes = await reader.LoadAsync(len); string data = reader.ReadString(numStrBytes); dlg.Title = "Received data"; dlg.Content = data; await dlg.ShowAsync(); }
/// <summary> /// Resolve the GEForce PC hostname to an IP Address /// </summary> /// <param name="hostName">Hostname to resolve</param> private async Task <String> ResolveHostName(String hostName) { HostName serverHost = new HostName(hostName); StreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket(); // Try to connect to the remote host try { await clientSocket.ConnectAsync(serverHost, "47984"); } catch (Exception e) { Debug.WriteLine("ResolveHostName Exception: " + e.Message); return(null); } return(clientSocket.Information.RemoteAddress.ToString()); }
/// <summary> /// Resolve the GEForce PC hostname to an IP Address /// </summary> /// <param name="hostName">Hostname to resolve</param> private async Task ResolveHostName(String hostName) { HostName serverHost = new HostName(hostName); StreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket(); // Try to connect to the remote host try { await clientSocket.ConnectAsync(serverHost, "http"); } // TODO properly handle this exception catch (Exception e) { Debug.WriteLine("Exception: " + e.Message); } this.ServerIP = clientSocket.Information.RemoteAddress.ToString(); }
/// <summary> /// established a TCP socket connection to receive packets from another device. /// This is used when running as a UWP app on the HoloLens. /// </summary> private async void ConnectSocketUWP() { try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(ipAddress); await socket.ConnectAsync(serverHost, portUWP); Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn, Encoding.UTF8); connection = true; } catch (Exception e) { //do something } }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR errorStatus = "UWP TCP client used in Unity!"; #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); streamIn = socket.InputStream.AsStreamForRead(); } catch (Exception e) { errorStatus = e.ToString(); } #endif }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR Debug.Log("Can't use UWP TCP client in Unity!"); #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); stream = socket.InputStream.AsStreamForRead(); Initialize(); Debug.Log("Connected!"); } catch (Exception e) { Debug.Log(e.ToString()); } #endif }
public async void StartClient(string Host, string PortNumber) { try { // Create the StreamSocket and establish a connection to the echo server. using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) { var hostName = new Windows.Networking.HostName(Host); await streamSocket.ConnectAsync(hostName, PortNumber); // Send a request to the echo server. string request = "Hello, World!"; using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(request); await streamWriter.FlushAsync(); } } // Read data from the echo server. string response; using (Stream inputStream = streamSocket.InputStream.AsStreamForRead()) { using (StreamReader streamReader = new StreamReader(inputStream)) { response = await streamReader.ReadLineAsync(); } } } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); } }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR Debug.Log("UWP TCP client used in Unity!"); #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); stream = socket.InputStream.AsStreamForRead(); #if !UNITY_EDITOR exchangeTask = Task.Run(() => Read_Data()); #endif Debug.Log("Connected!"); } catch (Exception e) { Debug.Log(e.ToString()); } #endif }
public static async Task StartClient() { try { // Create the StreamSocket and establish a connection to the echo server. streamSocket = new Windows.Networking.Sockets.StreamSocket(); // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName("192.168.0.137"); MainPage.MP.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, "1234"); MainPage.MP.clientListBox.Items.Add("client connected"); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
//This one is used to make a connection #else private async void ConnectUWP(string host, int port) { try { //Connect using streamSockets socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port.ToString()); //Set up asynchronous reading Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); //Make thread to read lines exchangeTask = Task.Run(() => DoReadUwp()); Debug.Log("Connected! uwp"); } catch (Exception e) { Debug.Log("uwp: " + e.ToString()); } }
private async void SocketListener_ConnectionReceived() { try { //Create the StreamSocket and establish a connection to the echo server. Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket(); //The server hostname that we will be establishing a connection to. We will be running the server and client locally, //so we will use localhost as the hostname. Windows.Networking.HostName serverHost = new Windows.Networking.HostName("raspberrypi"); //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc. //For the echo server/client application we will use a random port 1337. string serverPort = "51717"; await socket.ConnectAsync(serverHost, serverPort); //Write data to the echo server. Stream streamOut = socket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(streamOut); string request = textBox.Text; await writer.WriteLineAsync(request); await writer.FlushAsync(); //Read data from the echo server. Stream streamIn = socket.InputStream.AsStreamForRead(); StreamReader reader = new StreamReader(streamIn); string response = await reader.ReadLineAsync(); textBox1.Text = response; socket.Dispose(); } catch (Exception e) { //Handle exception here. } }
public async Task <string> Connect() { var rfcommServices = await bluetoothDeviced.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { try { var service = rfcommServices.Services[0]; // await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName); _service = service; // Create a socket and connect to the target _socket = new StreamSocket(); await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel .BluetoothEncryptionAllowNullAuthentication); sost = true; inputStream = _socket.InputStream.AsStreamForRead(); streamReader = new StreamReader(inputStream); return("Connect"); } catch (Exception ex) { sost = false; return(ex.Message); } } sost = false; return("0"); }
private async void StartClient() { int i = 0; while (true) { if (!UWconnectedflag) { UI_Stream_ready_flag = false; DRBE_softwarePage.UI_Stream_ready_flag = false; DRBE_ap.UI_Stream_ready_flag = false; try { // Create the StreamSocket and establish a connection to the echo server. DRBE_frontPage.Statues_tb.Text += "\r\n Client Try to Connect"; await Task.Delay(300); await UWstreamsocket.ConnectAsync(UWhostname, UWPportnumber); DRBE_frontPage.Statues_tb.Text += "\r\n Client Connected: " + UWstreamsocket.Information.LocalAddress.ToString(); DRBE_frontPage.DRBE_controlpanel.Message_tb.Text += "\r\n" + DateTime.Now.ToString("HH: mm: ss~~") + "Server Connected"; DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Text = "Connected"; DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Foreground = green_bright_button_brush; UWconnectedflag = true; UWoutputstream = UWstreamsocket.OutputStream.AsStreamForWrite(); UWinputstream = UWstreamsocket.InputStream.AsStreamForRead(); UWbinarywriter = new BinaryWriter(UWoutputstream); UWbinaryreader = new BinaryReader(UWinputstream); DRBE_softwarePage.UWbinarywriter = UWbinarywriter; DRBE_softwarePage.UI_Stream_ready_flag = true; DRBE_ap.UWbinarywriter = UWbinarywriter; DRBE_ap.UI_Stream_ready_flag = true; UI_Stream_ready_flag = true; testpacket = new List <byte>(mpacket.Pass(new List <byte>())); await Task.Delay(500); //UWbinarywriter.Write(testpacket.ToArray(), 0, 255); //UWbinarywriter.Flush(); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; string path = storageFolder.Path; List <byte> tosend = new List <byte>(); byte[] tbytes = Encoding.ASCII.GetBytes(path); tosend = new List <byte>(tbytes); UInt16 totallen = Convert.ToUInt16(tosend.Count() + 3); tosend.Insert(0, BitConverter.GetBytes(totallen)[0]); tosend.Insert(0, BitConverter.GetBytes(totallen)[1]); tosend.Insert(0, 0x90); UWbinarywriter.Write(tosend.ToArray(), 0, tosend.Count); UWbinarywriter.Flush(); ClientReading(); break; } catch (Exception ex) { await Task.Delay(1000); i++; } } } //} }
private async Task StartSocketClient() { try { string port = tbPort.Text; string svr = tbSvrName.Text; //// Create the StreamSocket and establish a connection to the echo server. //using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) //{ streamSocket = new Windows.Networking.Sockets.StreamSocket(); // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. string host = tbSvrName.Text; port = tbPort.Text; var hostName = new Windows.Networking.HostName(host); MainPage.MP.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, port); _Mode = Mode.JustConnected; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { status.Text = "Socket Connected. Getting config data"; }); MainPage.MP.clientListBox.Items.Add("client connected"); string request = "Hello, World"; outputStream = streamSocket.OutputStream.AsStreamForWrite(); streamWriter = new StreamWriter(outputStream); await streamWriter.WriteLineAsync(request); await streamWriter.FlushAsync(); MainPage.MP.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request)); // Read data from the echo server. string response; string json1 = ""; string json2 = ""; char[] chars = new char[1000]; chars[1] = 'Z'; int responseLength; inputStream = streamSocket.InputStream.AsStreamForRead(); streamReader = new StreamReader(inputStream); response = await streamReader.ReadLineAsync(); recvdText.Text = "" + response; responseLength = await streamReader.ReadAsync(chars, 0, 1000); recvdText.Text = "" + chars[0]; if (chars[0] == '@') { _Mode = Mode.JustConnected; await streamWriter.WriteAsync('0'); await streamWriter.FlushAsync(); } responseLength = await streamReader.ReadAsync(chars, 0, 1); recvdText.Text = "" + chars[0]; if (chars[0] == '1') { _Mode = Mode.ACK1; await streamWriter.WriteAsync('2'); await streamWriter.FlushAsync(); } responseLength = await streamReader.ReadAsync(chars, 0, 1); recvdText.Text = "" + chars[0]; if (chars[0] == '3') { _Mode = Mode.ACK3; await streamWriter.WriteAsync('4'); await streamWriter.FlushAsync(); } responseLength = await streamReader.ReadAsync(chars, 0, 1); recvdText.Text = "" + chars[0]; if (chars[0] == '5') { _Mode = Mode.ACK5; await streamWriter.WriteAsync('!'); await streamWriter.FlushAsync(); } responseLength = await streamReader.ReadAsync(chars, 0, 1); recvdText.Text = "" + chars[0]; if (chars[0] == '/') { await streamWriter.WriteAsync('/'); await streamWriter.FlushAsync(); _Mode = Mode.AwaitJson; json1 = await streamReader.ReadLineAsync(); recvdText.Text = json1; _Mode = Mode.JsonConfig; await MainPage.MP.UpdateTextAsync(json1); await streamWriter.WriteAsync('~'); await streamWriter.FlushAsync(); json2 = await streamReader.ReadLineAsync(); recvdText.Text = "" + json2; _Mode = Mode.Config; await MainPage.MP.UpdateTextAsync(json2); recvdText.Text = ""; _Mode = Mode.Running; Listen(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { status.Text = "Config data received: Press [Back]"; this.buttonStartRecv.IsEnabled = false; this.buttonStopRecv.IsEnabled = false; }); } MainPage.MP.clientListBox.Items.Add(string.Format("client received the response: \"{0}\" ", "Got Json")); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
/// <summary> /// Creates the stream the NmeaDevice is working on top off. /// </summary> /// <returns></returns> protected override async Task <System.IO.Stream> OpenStreamAsync() { var socket = new Windows.Networking.Sockets.StreamSocket(); socket.Control.KeepAlive = true; if (m_devicePeer != null) { await socket.ConnectAsync(m_devicePeer.HostName, "1"); } else { await socket.ConnectAsync(m_deviceService.ConnectionHostName, m_deviceService.ConnectionServiceName); } m_socket = socket; return(null); //We're going to use WinRT buffers instead and will handle read/write, so no reason to return a stream. This is mainly done to avoid locking issues reading and writing at the same time }