public async Task <Result> ReadVariable(string pVarName) { Result result = new Result(); // Read Variable request packet structure example: // 0 1 2 3 4 5 6 // xx xx | 00 0A | 00 | 00 07 | 24 4F 56 5F 50 52 4F // | 10 | 0 | 7 | $ O V _ P R O // REQ ID | REQ LEN | READ=00 | VAR NAME LEN | VAR NAME CHARS // (RANDOM)| if (pVarName.Length == 0) { result.ErrorMessage = "No variable was written"; return(result); } var PKT_var_name = new byte[pVarName.Length]; PKT_var_name = Encoding.UTF8.GetBytes(pVarName); var PKT_name_length = new byte[2]; PKT_name_length[0] = (byte)((pVarName.Length >> 8) & 255); PKT_name_length[1] = (byte)(pVarName.Length & 255); byte PKT_mode_is_read = 0; var PKT_req_len = new byte[2]; PKT_req_len[0] = (byte)(((pVarName.Length + 3) >> 8) & 255); PKT_req_len[1] = (byte)((pVarName.Length + 3) & 255); var PKT_req_id = new byte[2]; PKT_req_id[0] = (byte)((_msgID >> 8) & 255); PKT_req_id[1] = (byte)(_msgID & 255); _msgID++; if (_msgID > _lastID) { _msgID = _firstID; } var REQ_packet = new byte[pVarName.Length + 7 + 1]; REQ_packet[0] = PKT_req_id[0]; REQ_packet[1] = PKT_req_id[1]; REQ_packet[2] = PKT_req_len[0]; REQ_packet[3] = PKT_req_len[1]; REQ_packet[4] = PKT_mode_is_read; REQ_packet[5] = PKT_name_length[0]; REQ_packet[6] = PKT_name_length[1]; PKT_var_name.CopyTo(REQ_packet, 7); DataWriter writer; using (writer = new DataWriter(_socket.OutputStream)) { // Set the Unicode character encoding for the output stream writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // Specify the byte order of a stream. writer.ByteOrder = ByteOrder.LittleEndian; // Gets the size of UTF-8 string. writer.MeasureString(Encoding.UTF8.GetString(REQ_packet)); // Write a string value to the output stream. writer.WriteBytes(REQ_packet); // Send the contents of the writer to the backing stream. try { await writer.StoreAsync(); await writer.FlushAsync(); } catch (Exception ex) { SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); result.ErrorMessage = (webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); return(result); } // In order to prolong the lifetime of the stream, detach it from the DataWriter writer.DetachStream(); } // Read Variable response packet structure example: // 0 1 2 3 4 5 6 // xx xx | 00 0A | 00 | 00 06 | 35 35 33 39 39 33 | 00 01 01 // | 10 | 0 | 6 | 5 5 3 9 9 3 | 0 1 1 // SAME AS| RSP LEN | READ=00 | VALUE LEN | VALUE CHARS | TRAILER // REQUEST| DataReader reader; ByteBuilder byteBuilder = new ByteBuilder(); using (reader = new DataReader(_socket.InputStream)) { // Read the length of the payload that will be received. reader.InputStreamOptions = InputStreamOptions.Partial; // The encoding and byte order need to match the settings of the writer we previously used. reader.UnicodeEncoding = Windows.Storage.Streams.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. try { do { await reader.LoadAsync(_readBuffer); var bytes = new Byte[reader.UnconsumedBufferLength]; reader.ReadBytes(bytes); byteBuilder.AppendBytes(bytes); // Keep reading until we consume the complete stream. }while (reader.UnconsumedBufferLength > 0); } catch (Exception ex) { SocketErrorStatus webErrorStatus = SocketError.GetStatus(ex.GetBaseException().HResult); result.ErrorMessage = (webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); return(result); } finally { reader.DetachStream(); } } var flattenedList = byteBuilder._bytes.SelectMany(bytes => bytes); var RSP_packet = flattenedList.ToArray(); try { int RSP_len = (RSP_packet[2] << 8) | RSP_packet[3]; int RSP_val_len = (RSP_packet[5] << 8) | RSP_packet[6]; result.Data = Encoding.ASCII.GetString(RSP_packet, 7, RSP_val_len); int RSP_read_status = RSP_packet[7 + (RSP_val_len + 2)]; if ((RSP_read_status > 0) & (RSP_val_len > 0) & (RSP_packet[0] == PKT_req_id[0]) & (RSP_packet[1] == PKT_req_id[1])) { result.Succeeded = true; return(result); } else { result.ErrorMessage = "Cannot be read"; return(result); } } catch (Exception ex) { result.ErrorMessage = ex.Message; return(result); } }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> public async void StartListener() { // Overriding the listener here is safe as it will be deleted once all references to it are gone. // However, in many cases this is a dangerous pattern to override data semi-randomly (each time user // clicked the button) so we block it here. if (CoreApplication.Properties.ContainsKey("listener")) { Util.Log( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(PortOrServicenameForListener)) { Util.Log("Please provide a service name.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); LocalHostItem selectedLocalHost = null; if ((BindToAddress_IsChecked == true) || (BindToAdapter_IsChecked == true)) { selectedLocalHost = new LocalHostItem(RemoteSocketListenerSvrName); if (selectedLocalHost == null) { Util.Log("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // If necessary, tweak the listener's control options before carrying out the bind operation. // These options will be automatically applied to the connected StreamSockets resulting from // incoming connections (i.e., those passed as arguments to the ConnectionReceived event handler). // Refer to the StreamSocketListenerControl class' MSDN documentation for the full list of control options. listener.Control.KeepAlive = false; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny_IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(PortOrServicenameForListener); Util.Log("Listening", NotifyType.StatusMessage); } else if (BindToAddress_IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, PortOrServicenameForListener); Util.Log( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); Util.Log( "On Port " + PortOrServicenameForListener, NotifyType.StatusMessage); } else if (BindToAdapter_IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overridden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; // For demo purposes, ensure that we use the same adapter in the client connect scenario. CoreApplication.Properties.Add("adapter", selectedAdapter); await listener.BindServiceNameAsync( PortOrServicenameForListener, SocketProtectionLevel.PlainSocket, selectedAdapter); Util.Log( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } Util.Log( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public void MainLoop() { try { bool shutdownCleanly = false; try { while (m_running) { try { MainLoopIteration(); } catch (SoftProtocolException spe) { QuiesceChannel(spe); } } shutdownCleanly = true; } catch (EndOfStreamException eose) { // Possible heartbeat exception HandleMainLoopException(new ShutdownEventArgs( ShutdownInitiator.Library, 0, "End of stream", eose)); } catch (HardProtocolException hpe) { shutdownCleanly = HardProtocolExceptionHandler(hpe); } #if !NETFX_CORE catch (Exception ex) { HandleMainLoopException(new ShutdownEventArgs(ShutdownInitiator.Library, Constants.InternalError, "Unexpected Exception", ex)); } #endif // If allowed for clean shutdown, run main loop until the // connection closes. if (shutdownCleanly) { #pragma warning disable 0168 try { ClosingLoop(); } #if NETFX_CORE catch (Exception ex) { if (SocketError.GetStatus(ex.HResult) != SocketErrorStatus.Unknown) { // means that socket was closed when frame handler // attempted to use it. Since we are shutting down, // ignore it. } else { throw ex; } } #else catch (SocketException se) { // means that socket was closed when frame handler // attempted to use it. Since we are shutting down, // ignore it. } #endif #pragma warning restore 0168 } FinishClose(); } finally { m_appContinuation.Set(); } }
private static NtpNetworkException ExceptionToNtpNetworkException(Exception ex) { return(new NtpNetworkException(ex.Message, (int)SocketError.GetStatus(ex.HResult), ex)); }
/// <summary> /// A client has connected (nothing has been sent or received yet) /// </summary> /// <returns></returns> private async void OnClientConnected(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (args == null || args.Socket == null) { return; } _logger.Debug("Connection from {0}:{1} to {2}:{3} was opened", args.Socket.Information.RemoteHostName.DisplayName, args.Socket.Information.RemotePort, args.Socket.Information.LocalAddress.DisplayName, args.Socket.Information.LocalPort); _logger.Trace("Pipeline => HttpServer.OnClientConnected"); ClientConnectedEventArgs connectedArgs = new ClientConnectedEventArgs(args); try { ClientConnected(sender, connectedArgs); if (connectedArgs.AllowConnect == false) { if (connectedArgs.Response != null) { await connectedArgs.Response.FlushAsync(); } _logger.Debug("Connection from {0}:{1} to {2}:{3} was denied access to connect", args.Socket.Information.RemoteHostName.DisplayName, args.Socket.Information.RemotePort, args.Socket.Information.LocalAddress.DisplayName, args.Socket.Information.LocalPort); } else { OnMessageReceived(connectedArgs.Socket); } } catch (Exception ex) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) { IsActive = false; ListenerError(_listener, ex); _logger.Error("Http request failed with error: {0}", ex.Message, ex); } else { OnClientDisconnected(_listener, ex, SocketError.GetStatus(ex.HResult)); } _logger.Debug("Connection from {0}:{1} to {2}:{3} was {4}", args.Socket.Information.RemoteHostName.DisplayName, args.Socket.Information.RemotePort, args.Socket.Information.LocalAddress.DisplayName, args.Socket.Information.LocalPort, SocketError.GetStatus(ex.HResult).ToString()); } }
async private void SendHello(uint sizeOfArray) { if (!CoreApplication.Properties.ContainsKey("connected")) { rootPage.NotifyUser("Please run previous steps before doing this one.", NotifyType.ErrorMessage); return; } object outValue; StreamSocket socket; if (!CoreApplication.Properties.TryGetValue("clientSocket", out outValue)) { rootPage.NotifyUser("Please run previous steps before doing this one.", NotifyType.ErrorMessage); return; } socket = (StreamSocket)outValue; // Create a DataWriter if we did not create one yet. Otherwise use one that is already cached. DataWriter writer; if (!CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue)) { writer = new DataWriter(socket.OutputStream); CoreApplication.Properties.Add("clientDataWriter", writer); } else { writer = (DataWriter)outValue; } writer.WriteUInt32(sizeOfArray); // Write first the length of the string as UINT32 value followed up by the string. // Writing data to the writer will just store data in memory. DateTime now = DateTime.Now; //string stringToSend = now.ToString("yyyy-MM-ddTHH:mm:ss.fff"); //writer.WriteUInt32(writer.MeasureString(stringToSend)); //writer.WriteString(stringToSend); for (int i = 0; i < sizeOfArray; i++) { writer.WriteSingle(dataInFloat[i]); } // Write the locally buffered data to the network. try { await writer.StoreAsync(); DateTime after = DateTime.Now; TimeSpan delay = after - now; Debug.WriteLine("RTT is " + delay.ToString() + " sent successfully."); } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser("Send failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
/// <summary> /// This is the click handler for the 'SendHello' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> public async Task <bool> Send(string SendData) { if (Sox.AppMode != AppMode.ClientSocketReadyToSend) { if (Sox.AppMode == AppMode.ClientSocketConnected) { Sox.Instance.Log( "Client send failed with warning: App Client Socket connected but not ready to send.", NotifyType.ErrorMessage); } else { Sox.Instance.Log( "Client send failed with error: App not in new Client Ready To Send Mode", NotifyType.ErrorMessage); } return(false); } string stringToSend = SendData;// "Hello"; if (!CoreApplication.Properties.ContainsKey("connected")) { Sox.Instance.Log("Client not connected.", NotifyType.ErrorMessage); return(false); } else { object outValue; StreamSocket socket; if (!CoreApplication.Properties.TryGetValue("clientSocket", out outValue)) { Sox.Instance.Log("Client socket not enabled.", NotifyType.ErrorMessage); return(false); } else { socket = (StreamSocket)outValue; // Create a DataWriter if we did not create one yet. Otherwise use one that is already cached. DataWriter writer; if (!CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue)) { writer = new DataWriter(socket.OutputStream); CoreApplication.Properties.Add("clientDataWriter", writer); } else { writer = (DataWriter)outValue; } // Write first the length of the string as UINT32 value followed up by the string. // Writing data to the writer will just store data in memory. string actualStringToSend = Passkey + stringToSend; writer.WriteUInt32(writer.MeasureString(actualStringToSend)); writer.WriteString(actualStringToSend); // Write the locally buffered data to the network. try { Sox.StartToken(); await writer.StoreAsync().AsTask(Sox.CancelToken); SendOutput = "\"" + stringToSend + "\" sent successfully."; } catch (TaskCanceledException) { Sox.Instance.Log("Canceled.", NotifyType.StatusMessage); return(false); } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } Sox.Instance.Log("Send failed with error: " + exception.Message, NotifyType.ErrorMessage); return(false); } } } return(true); }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceName.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } if (listenerSocket != null) { rootPage.NotifyUser("A listener socket is already set up.", NotifyType.ErrorMessage); return; } bool isMulticastSocket = (MulticastRadioButton.IsChecked == true); listenerSocket = new DatagramSocket(); listenerSocket.MessageReceived += MessageReceived; if (isMulticastSocket) { // DatagramSockets conduct exclusive (SO_EXCLUSIVEADDRUSE) binds by default, effectively blocking // any other UDP socket on the system from binding to the same local port. This is done to prevent // other applications from eavesdropping or hijacking a DatagramSocket's unicast traffic. // // Setting the MulticastOnly control option to 'true' enables a DatagramSocket instance to share its // local port with any Win32 sockets that are bound using SO_REUSEADDR/SO_REUSE_MULTICASTPORT and // with any other DatagramSocket instances that have MulticastOnly set to true. However, note that any // attempt to use a multicast-only DatagramSocket instance to send or receive unicast data will result // in an exception being thrown. // // This control option is particularly useful when implementing a well-known multicast-based protocol, // such as mDNS and UPnP, since it enables a DatagramSocket instance to coexist with other applications // running on the system that also implement that protocol. listenerSocket.Control.MulticastOnly = true; } // Start listen operation. try { await listenerSocket.BindServiceNameAsync(ServiceName.Text); if (isMulticastSocket) { // Join the multicast group to start receiving datagrams being sent to that group. listenerSocket.JoinMulticastGroup(new HostName(RemoteAddress.Text)); rootPage.NotifyUser( "Listening on port " + listenerSocket.Information.LocalPort + " and joined to multicast group", NotifyType.StatusMessage); } else { rootPage.NotifyUser( "Listening on port " + listenerSocket.Information.LocalPort, NotifyType.StatusMessage); } // Enable scenario steps that require us to have an active listening socket. SendMessageButton.IsEnabled = true; CloseListenerButton.IsEnabled = true; } catch (Exception exception) { listenerSocket.Dispose(); listenerSocket = null; // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public async void Connect(Uri uri) { if (ConnectionState != ConnectionStateType.Disconnected) { switch (ConnectionState) { case ConnectionStateType.Connecting: Notify("Connecting...", NotifyType.ErrorMessage); break; case ConnectionStateType.Connected: Notify("Already connected.", NotifyType.ErrorMessage); break; default: break; } return; } try { Notify("Trying to connect ...", NotifyType.StatusMessage); if (clientSocket == null) { clientSocket = new StreamSocket(); } ConnectionState = ConnectionStateType.Connecting; // Set timeout 3 sec canclConnect = new CancellationTokenSource(); canclConnect.CancelAfter(1000); // Try to connect to the await clientSocket.ConnectAsync(new HostName(uri.Host), uri.Port.ToString(), SocketProtectionLevel.PlainSocket).AsTask(canclConnect.Token); ConnectionState = ConnectionStateType.Connected; Notify("Connection established", NotifyType.StatusMessage); } catch (TaskCanceledException exception) { Notify("Connection timedout: " + exception.Message, NotifyType.ErrorMessage); // the Close method is mapped to the C# Dispose if (clientSocket != null) { clientSocket.Dispose(); } clientSocket = null; ConnectionState = ConnectionStateType.Disconnected; } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } Notify("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); // the Close method is mapped to the C# Dispose if (clientSocket != null) { clientSocket.Dispose(); } clientSocket = null; ConnectionState = ConnectionStateType.Disconnected; } }
async void Connect(object sender, RoutedEventArgs e) { rootPage.NotifyUser("", NotifyType.ErrorMessage); DeviceInformation chosenDevInfo = null; EndpointPair endpointPair = null; try { // If nothing is selected, return if (FoundDevicesList.SelectedIndex == -1) { rootPage.NotifyUser("Please select a device", NotifyType.StatusMessage); return; } else { chosenDevInfo = devInfoCollection[FoundDevicesList.SelectedIndex]; } rootPage.NotifyUser("Connecting to " + chosenDevInfo.Name + "....", NotifyType.StatusMessage); // Connect to the selected WiFiDirect device wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(chosenDevInfo.Id); if (wfdDevice == null) { rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage); return; } // Register for Connection status change notification wfdDevice.ConnectionStatusChanged += new TypedEventHandler <Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(DisconnectNotification); // Get the EndpointPair collection var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs(); if (EndpointPairCollection.Count > 0) { endpointPair = EndpointPairCollection[0]; } else { rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage); return; } PCIpAddress.Text = "PC's IP Address: " + endpointPair.LocalHostName.ToString(); DeviceIpAddress.Text = "Device's IP Address: " + endpointPair.RemoteHostName.ToString(); PCIpAddress.Visibility = Visibility.Visible; DeviceIpAddress.Visibility = Visibility.Visible; //SendTextButton.Visibility = Visibility.Visible; DisconnectButton.Visibility = Visibility.Visible; ConnectButton.Visibility = Visibility.Collapsed; FoundDevicesList.Visibility = Visibility.Collapsed; GetDevicesButton.Visibility = Visibility.Collapsed; rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage); //Server Socket open StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // Start listen operation. try { // bind to any // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync("9190"); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); // bind to specific address // Try to bind to a specific address. //BindEndpointAsync(Target IPAddr, Port Number) //HostName DeviceIPHostName = new HostName(endpointPair.RemoteHostName.ToString()); //await listener.BindEndpointAsync(DeviceIPHostName, "9190"); //rootPage.NotifyUser( // "Listening on address " + DeviceIPHostName.ToString(), NotifyType.StatusMessage); } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } } catch (Exception err) { rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed: " + err.Message, NotifyType.ErrorMessage); } }
public async void WriteToLight(double red, double green, double blue, double brightness) { if (isConnected) { /********************************************************** * This is a port from https://www.npmjs.com/package/rgb-led * Credits to: * Secesh aka Matthew R Chase ([email protected]) * This is the core of the protocol we discovered. Commands * look like this: * [STX], [RED], [GREEN], [BLUE], [ETX] * Each field is a hex byte with possible values 00-FF, which * are expressed in decimal as 0-255. * * Each command starts (the STX value) with a value of 86. * Each command ends (the ETX value) with a value of 170. * * The red, green, blue values combine to determine the color * and brightness level. For example: * * Bright red would be: 255,0,0 * reduce the value to dim; a dim red could be: 40,0,0 * Bright green would be: 0,255,0 * Bright purple would be: 255,0,255 * a dim purple could be 40,0,40 * a less dim purple could be 160,0,160 * * White is: 255,255,255 * Off is: 0,0,0 ************************************************************/ red = Math.Round(red * brightness / 100); green = Math.Round(green * brightness / 100); blue = Math.Round(blue * brightness / 100); DataWriter writer = new DataWriter(socket.OutputStream); // Create the data writer object backed by the in-memory stream. using (writer = new DataWriter(socket.OutputStream)) { var message = new int[] { 86, Convert.ToInt32(red), Convert.ToInt32(green), Convert.ToInt32(blue), 170 }; byte[] messageBytes = message.SelectMany(value => BitConverter.GetBytes(value)).ToArray(); writer.WriteBytes(messageBytes); // Send the contents of the writer to the backing stream. try { await writer.StoreAsync(); } catch (Exception exception) { switch (SocketError.GetStatus(exception.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error Debug.WriteLine("LED Host/Port not found"); break; default: // If this is an unknown status it means that the error is fatal and retry will likely fail. Debug.WriteLine(exception.Message); break; } } await writer.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter writer.DetachStream(); } } else { Debug.WriteLine("LED not connected"); } }
public async Task <bool> Connect() { if (_connected) { return(false); } try { _serverHost = new Windows.Networking.HostName(_IPAddress); _clientSocket.Control.KeepAlive = true; // Try to connect to the await _clientSocket.ConnectAsync(_serverHost, _port); _connected = true; } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } // Could retry the connection, but for this simple example // just close the socket. _closing = true; // the Close method is mapped to the C# Dispose _clientSocket.Dispose(); _clientSocket = null; return(false); } if (_connected) { return(true); } try { _clientSocket.Control.KeepAlive = true; _serverHost = new Windows.Networking.HostName(_IPAddress); // Try to connect to the await _clientSocket.ConnectAsync(_serverHost, _port); _connected = true; return(_connected); } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } // Could retry the connection, but for this simple example // just close the socket. _closing = true; // the Close method is mapped to the C# Dispose _clientSocket.Dispose(); _clientSocket = null; return(false); } }
/// <summary> /// 接收数据 /// </summary> /// <returns></returns> private async Task BeginReceived() { //绑定已连接的StreamSocket到DataReader DataReader reader = new DataReader(clientSocket.InputStream); while (true) { try { byte[] tempByteArr; //获取数据长度 tempByteArr = new byte[4]; await reader.LoadAsync(sizeof(uint)); reader.ReadBytes(tempByteArr); uint dataLength = System.BitConverter.ToUInt32(tempByteArr, 0); //StatusText.Text = dataLength.ToString(); //获取msgID tempByteArr = new byte[4]; await reader.LoadAsync(sizeof(int)); reader.ReadBytes(tempByteArr); int msgID = System.BitConverter.ToInt32(tempByteArr, 0); //读完数据头 tempByteArr = new byte[32]; await reader.LoadAsync(32); reader.ReadBytes(tempByteArr); if (dataLength > 0) { //读取数据正文 tempByteArr = new byte[dataLength]; await reader.LoadAsync(dataLength); reader.ReadBytes(tempByteArr); StatusText.Text = System.Text.UnicodeEncoding.UTF8.GetString(tempByteArr, 0, int.Parse(dataLength.ToString())); } else { StatusText.Text = ""; } } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } StatusText.Text = "Send data or receive failed with error: " + exception.Message; // Could retry the connection, but for this simple example // just close the socket. closing = true; clientSocket.Dispose(); clientSocket = null; connected = false; } } }
//int frameCount = 0; async void Discover() { Debug.Log("Discovering..."); //make handshake with TCP_client, and the port is set to be 4444 tcpSocket = new StreamSocket(); HostName networkHost = new HostName(CommandSet.IP.Trim()); try { await tcpSocket.ConnectAsync(networkHost, CommandSet.DISCOVERY_PORT.ToString()); Debug.Log("tcpSocket Connected!"); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } //Write data to the echo server. Stream streamOut = tcpSocket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(streamOut); //when the drone receive the message bellow, it will return the confirmation string handshake_Message = "{\"controller_type\":\"computer\", \"controller_name\":\"halley\", \"d2c_port\":\"43210\", \"arstream2_client_stream_port\":\"55004\",\"arstream2_client_control_port\":\"55005\"}"; try { await writer.WriteLineAsync(handshake_Message); await writer.FlushAsync(); Debug.Log("tcpSocket writer successful!"); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } //Read data from the echo server. Stream streamIn = tcpSocket.InputStream.AsStreamForRead(); StreamReader reader = new StreamReader(streamIn); string receive_Message = await reader.ReadLineAsync(); if (receive_Message == null) { Debug.Log("Discover failed"); //return -1; isConnected = false; } else { Debug.Log("The message from the drone shows: " + receive_Message); //initialize initPCMD(); initCMD(); //All State setting generateAllStates(); generateAllSettings(); isConnected = true; Debug.Log("isConnected = true"); pcmdThreadActive(); //return 1; } }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { temp = "connected!"; DataReader reader = new DataReader(args.Socket.InputStream); DataWriter writer = new DataWriter(args.Socket.OutputStream); try { while (true) { //发送数据格式: 命令(1) 长度(1) 数据(长度) byte[] ba = { 0 }; //读取命令,1字节 uint actualLength = await reader.LoadAsync(1); if (actualLength != 1) { return; //socket提前close()了 } command = uint.Parse(reader.ReadByte().ToString()); //解析命令 //读取数据长度, 1字节 actualLength = await reader.LoadAsync(1); if (actualLength != 1) { return; } uint dataLength = uint.Parse(reader.ReadByte().ToString());; //解析数据长度 // Matrix4x4[] matrixGroup; //读取所有数据,matrixlength长度 if (dataLength != 0) { bDataOK = true; actualLength = await reader.LoadAsync(dataLength); if (actualLength != dataLength) { return;//socket提前close()了 } uint numberOfMatrix = dataLength / 64; if (numberOfMatrix < 1) { return; //未收到一个矩阵 } matrixGroup = new Matrix4x4[numberOfMatrix]; for (int i = 0; i < numberOfMatrix; i++) { for (int j = 0; j < 4; j++) { float[] column = new float[4]; for (int k = 0; k < 4; k++) { byte[] temp = new byte[4]; reader.ReadBytes(temp); column[k] = BitConverter.ToSingle(temp, 0); } matrixGroup[i].SetColumn(j, new Vector4(column[0], column[1], column[2], column[3])); } } } //返回一个初始化的矩阵做测试 Matrix4x4 mat = new Matrix4x4(); //这里为要发送的矩阵 mat = fanhui; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { byte[] b = BitConverter.GetBytes(mat[j, i]); writer.WriteBytes(b); } } await writer.StoreAsync(); Debug.Log("Return Matrixs"); bDataOK = true; } } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } }
public void startReaderTask() { if (state != ConnectionState.CONNECTED) { throw new InvalidOperationException("[TCPConnection2]: Unable to start reader task! ConnectionState != CONNECTED - state = " + state); } // Ensure no other reader task is running: if (readingCTS != null && !readingCTS.IsCancellationRequested) { readingCTS.Cancel(); } readingCTS = new CancellationTokenSource(); try { Task.Run(async() => { TCPReadResult readResult = null; int lastReadingFailedCount = 0; int errorCount = 0; DateTime lastReadingFailed = DateTime.MinValue; while (state == ConnectionState.CONNECTED && errorCount < 3) { try { readResult = await readAsync(); // Check if reading failed: switch (readResult.STATE) { case TCPReadState.SUCCESS: lastReadingFailedCount = 0; errorCount = 0; Logger.Debug("[TCPConnection2]: Received from (" + account.serverAddress + "):" + readResult.DATA); // Trigger the NewDataReceived event: NewDataReceived?.Invoke(this, new NewDataReceivedEventArgs(readResult.DATA)); break; case TCPReadState.FAILURE: if (lastReadingFailedCount++ <= 0) { lastReadingFailed = DateTime.Now; } // Read 5 empty or null strings in an interval lower than 1 second: double c = DateTime.Now.Subtract(lastReadingFailed).TotalSeconds; if (lastReadingFailedCount > 5 && c < 1) { lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_LOOP); errorCount = int.MaxValue; continue; } break; case TCPReadState.END_OF_STREAM: Logger.Info("Socket closed because received 0-length message from: " + account.serverAddress); disconnect(); break; } } catch (OperationCanceledException) { lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_CANCELED); errorCount++; } catch (Exception e) { SocketErrorStatus status = SocketErrorStatus.Unknown; if (e is AggregateException aggregateException && aggregateException.InnerException != null) { status = SocketError.GetStatus(e.InnerException.HResult); } else { Exception baseException = e.GetBaseException(); if (baseException != null) { status = SocketError.GetStatus(e.GetBaseException().HResult); } else { status = SocketError.GetStatus(e.HResult); } } lastConnectionError = new ConnectionError(status, e.Message); switch (status) { // Some kind of connection lost: case SocketErrorStatus.ConnectionTimedOut: case SocketErrorStatus.ConnectionRefused: case SocketErrorStatus.NetworkDroppedConnectionOnReset: case SocketErrorStatus.SoftwareCausedConnectionAbort: case SocketErrorStatus.ConnectionResetByPeer: errorCount = int.MaxValue; break; default: errorCount++; break; } }
void PrintException(string from, Exception exception) { Log(from + " " + SocketError.GetStatus(exception.HResult).ToString()); }
private async void StartListener_Click(object sender, RoutedEventArgs e) { // Overriding the listener here is safe as it will be deleted once all references to it are gone. // However, in many cases this is a dangerous pattern to override data semi-randomly (each time user // clicked the button) so we block it here. if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); CoreApplication.Properties.Remove("adapter"); LocalHostItem selectedLocalHost = null; selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // If necessary, tweak the listener's control options before carrying out the bind operation. // These options will be automatically applied to the connected StreamSockets resulting from // incoming connections (i.e., those passed as arguments to the ConnectionReceived event handler). // Refer to the StreamSocketListenerControl class' MSDN documentation for the full list of control options. listener.Control.KeepAlive = false; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
/// <summary> /// This is the click handler for the 'ConnectSocket' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (CoreApplication.Properties.ContainsKey("clientSocket")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(ServiceNameForConnect.Text)) { rootPage.NotifyUser("Please provide a service name.", 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("Error: Invalid host name.", NotifyType.ErrorMessage); return; } StreamSocket socket = new StreamSocket(); // If necessary, tweak the socket's control options before carrying out the connect operation. // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options. socket.Control.KeepAlive = false; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("clientSocket", socket); try { if (adapter == null) { rootPage.NotifyUser("Connecting to: " + HostNameForConnect.Text, NotifyType.StatusMessage); // Connect to the server (by default, the listener we created in the previous step). await socket.ConnectAsync(hostName, ServiceNameForConnect.Text); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); } else { rootPage.NotifyUser( "Connecting to: " + HostNameForConnect.Text + " using network adapter " + adapter.NetworkAdapterId, NotifyType.StatusMessage); // Connect to the server (by default, the listener we created in the previous step) // limiting traffic to the same adapter that the user specified in the previous step. // This option will be overridden by interfaces with weak-host or forwarding modes enabled. await socket.ConnectAsync( hostName, ServiceNameForConnect.Text, SocketProtectionLevel.PlainSocket, adapter); rootPage.NotifyUser( "Connected using network adapter " + adapter.NetworkAdapterId, NotifyType.StatusMessage); } // Mark the socket as connected. Set the value to null, as we care only about the fact that the // property is set. CoreApplication.Properties.Add("connected", null); } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
private static string GetErrorText(Exception ex) { return(string.Format("{0} ({1})", ex.Message, SocketError.GetStatus(ex.GetBaseException().HResult))); }
public async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action <string, byte[]> onResponse, CancellationToken cancellationToken) { using (var socket = new DatagramSocket()) { // setup delegate to detach from later TypedEventHandler <DatagramSocket, DatagramSocketMessageReceivedEventArgs> handler = (sock, args) => { var dr = args.GetDataReader(); var buffer = dr.ReadBuffer(dr.UnconsumedBufferLength).ToArray(); onResponse(args.RemoteAddress.CanonicalName.ToString(), buffer); }; socket.MessageReceived += handler; var socketBound = false; for (var i = 0; i < retries; i++) { cancellationToken.ThrowIfCancellationRequested(); try { await BindToSocketAndWriteQuery(socket, requestBytes, cancellationToken).ConfigureAwait(false); socketBound = true; } catch (Exception e) { socketBound = false; Debug.WriteLine("Exception trying to Bind:\n{0}", e); // Most likely a fatal error if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown) { throw; } // If we're not connected on the last retry, rethrow the underlying exception if (i + 1 >= retries) { throw; } } if (socketBound) { break; } Debug.WriteLine("Retrying in {0} ms", retryDelayMilliseconds); // Not found, wait to try again await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } if (socketBound) { // wait for responses await Task.Delay(scanTime, cancellationToken).ConfigureAwait(false); Debug.WriteLine("Done Scanning"); } } }
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { while (true) { reader = new DataReader(args.Socket.InputStream); // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } string s = reader.ReadString(actualStringLength); // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. NotifyUserFromAsyncThread( String.Format("Received data: \"{0}\"", s), NotifyType.StatusMessage); bool t = s.ToLower().Contains("on"); bool f = s.ToLower().Contains("off"); if (t) { if (bGpioStatus) { pinValue = GpioPinValue.High; myPin.Write(pinValue); NotifyUserFromAsyncThreadBulb(1); } } else if (f) { if (bGpioStatus) { pinValue = GpioPinValue.Low; myPin.Write(pinValue); NotifyUserFromAsyncThreadBulb(0); } } //reader.DetachStream(); } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } //SendMessage.Text = // "Read stream failed with error: " + exception.Message; } }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); DatagramSocket listener = new DatagramSocket(); listener.MessageReceived += MessageReceived; if (!String.IsNullOrWhiteSpace(InboundBufferSize.Text)) { uint inboundBufferSize = 0; if (!uint.TryParse(InboundBufferSize.Text, out inboundBufferSize)) { rootPage.NotifyUser( "Please provide a positive numeric Inbound buffer size.", NotifyType.ErrorMessage); return; } try { // Running both client and server on localhost will most likely not reach the buffer limit. listener.Control.InboundBufferSizeInBytes = inboundBufferSize; } catch (ArgumentException) { rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage); return; } } LocalHostItem selectedLocalHost = null; if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny.IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overriden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter); rootPage.NotifyUser( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
/// <summary> /// This is the click handler for the 'ConnectSocket' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceNameForConnect.Text)) { rootPage.NotifyUser("Please provide a service name.", 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("Error: Invalid host name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("clientSocket")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } DatagramSocket socket = new DatagramSocket(); if (DontFragment.IsOn) { // Set the IP DF (Don't Fragment) flag. // This won't have any effect when running both client and server on localhost. // Refer to the DatagramSocketControl class' MSDN documentation for the full list of control options. socket.Control.DontFragment = true; } socket.MessageReceived += MessageReceived; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("clientSocket", socket); rootPage.NotifyUser("Connecting to: " + HostNameForConnect.Text, NotifyType.StatusMessage); try { // Connect to the server (by default, the listener we created in the previous step). await socket.ConnectAsync(hostName, ServiceNameForConnect.Text); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); // Mark the socket as connected. Set the value to null, as we care only about the fact that the // property is set. CoreApplication.Properties.Add("connected", null); } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
/// <summary> /// Invoked once a connection is accepted by StreamSocketListener. /// </summary> /// <param name="sender">The listener that accepted the connection.</param> /// <param name="args">Parameters associated with the accepted connection.</param> private async void OnConnection( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { DataReader reader = new DataReader(args.Socket.InputStream); try { //Windows.Storage.Streams.Buffer Out = new Windows.Storage.Streams.Buffer(100); //await args.Socket.OutputStream.WriteAsync(Out); while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } string data = reader.ReadString(actualStringLength); await NotifyUserFromAsyncThread( String.Format("Received data: \"{0}\"", data), NotifyType.StatusMessage); if (data.Length > 0) { char command = data[0]; string param = data.Substring(1); switch (command) { //case 'C': // await RemoteControl.RemoteActions(Enums.Item.CameraToggle); // break; //case 'T': // await RemoteControl.RemoteActions(Enums.Item.TakePhoto); // break; //case 'N': // await RemoteControl.RemoteActions(Enums.Item.NoFlash); // break; //case 'A': // await RemoteControl.RemoteActions(Enums.Item.AutoFlash); // break; //case 'F': // await RemoteControl.RemoteActions(Enums.Item.Flash); // break; //case 'V': // await RemoteControl.RemoteActions(Enums.Item.Video); // break; //case 'a': // await RemoteControl.RemoteActions(Enums.Item.AutoFocus); // break; //case 'm': // if (param != "") // await RemoteControl.RemoteActions(Enums.Item.ManualFocus); // else // await RemoteControl.RemoteActions(Enums.Item.ManualFocus, param); // break; //case 'G': // await RemoteControl.RemoteActions(Enums.Item.GPS); // break; //case 'Z': // await RemoteControl.RemoteActions(Enums.Item.Zoom, param); // break; } } //}); // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } await NotifyUserFromAsyncThread( "Read stream failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
private async Task ProcessMessages() { using (StreamSocket socket = new StreamSocket()) { HostName hostname = new HostName(string.Format("({0})", MeterMateId)); //HostName hostname = new HostName("(00:0A:4F:01:21:78)"); socket.Control.NoDelay = false; string command = string.Empty; try { // Connect to the Bluetooth device await socket.ConnectAsync(hostname, "{00001101-0000-1000-8000-00805f9b34fb}"); while (true) { // Check if we should stop if (stopProcessing) { break; } // Get the command name command = await ReadResponse(socket); if (!string.IsNullOrWhiteSpace(command)) { txtOutput.Text = command; // Parse the JSON JsonObject json = JsonObject.Parse(command); string commandType = json.GetNamedString("Command"); if (string.Compare(commandType, "gt", StringComparison.OrdinalIgnoreCase) == 0) { await ProcessTemperature(json); } else if (string.Compare(commandType, "gs", StringComparison.OrdinalIgnoreCase) == 0) { await ProcessStatus(json); } } else { Debug.WriteLine("Not connected. Retrying ..."); txtOutput.Text = "OBC Not connected.\r\nConnect & restart app."; StopProcessing(); } } } catch (Exception ex) { string err = ex.Message; txtOutput.Text = err; SocketErrorStatus ses = SocketError.GetStatus(ex.HResult); StopProcessing(); } finally { socket.Dispose(); } } }
// message recieved handlers #if !UNITY_EDITOR private async void Prim_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { if (jpgReady || decoding) { //Debug.Log("Ignoring recieved jpg, already one ready for processing"); return; } Debug.Log("Prim_MessageReceived Event: primary socket... updating content."); // setup read operation int messageLength = -1; // set to invalid state intitally DataReader messageReader = args.GetDataReader(); messageReader.ByteOrder = ByteOrder.LittleEndian; try { messageLength = messageReader.ReadInt32(); // first 4 bytes of all messages must be int32 indicating length (all inclusive) // next line (LoadAsync) causes System.Runtime.InteropServices.COMException... alternate solution implemented below //await messageReader.LoadAsync((uint)messageLength); // did not fix error.. just not LoadAsync'ing //IAsyncOperation<uint> loadTask = messageReader.LoadAsync((uint)messageLength); //loadTask.AsTask().Wait(); } catch (Exception ex) { Debug.Log(string.Format("Exception setting up message read: {0}", ex.ToString())); Debug.Log(SocketError.GetStatus(ex.HResult).ToString()); } // read header (as int32s) int[] header = new int[0]; // set to invalid state initally try { header = new int[HEADER_SIZE_PRIM / 4]; // 4 bytes per int for (int i = 0; i < HEADER_SIZE_PRIM / 4; i++) { header[i] = messageReader.ReadInt32(); } } catch (Exception ex) { Debug.Log(string.Format("Exception reading message header: {0}", ex.ToString())); Debug.Log(SocketError.GetStatus(ex.HResult).ToString()); } // read body (as bytes) byte[] body = new byte[0]; // set to invalid state initally try { int bodyLength = messageLength - HEADER_SIZE_PRIM - 4; body = new byte[bodyLength]; messageReader.ReadBytes(body); } catch (Exception ex) { Debug.Log(string.Format("Exception reading message body: {0}", ex.ToString())); Debug.Log(SocketError.GetStatus(ex.HResult).ToString()); } // debug Debug.Log(string.Format("PMRE: About to process message body. Body length: {0}", body.Length)); // split handling based on mode if (Mode == Trans_Mode.fullFile) { FullFileMode_PMRE(body); } else if (Mode == Trans_Mode.fileName) { FileNameMode_PMRE(body); } // debug Debug.Log(string.Format("Prim_MessageReceived Event: Completed PMRE")); }
/// <summary> /// This is the click handler for the 'ConnectSocket' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> public async Task ConnectSocket() { if (Sox.AppMode != AppMode.NewClient) { if (Sox.AppMode == AppMode.ClientSocketConnected) { Sox.Instance.Log( "Start client failed with warning: App Client Socket already connected", NotifyType.WarningMessage); } else { Sox.Instance.Log( "Start client failed with error: App not in new Client Mode", NotifyType.ErrorMessage); } } else { HostName hostName = null; if (CoreApplication.Properties.ContainsKey("clientSocket")) { Sox.Instance.Log( "This step has already been executed.", NotifyType.ErrorMessage); //return; } else { if (string.IsNullOrEmpty(PortOrServicenameForListener)) //(String.IsNullOrEmpty(ServiceNameForConnect)) { Sox.Instance.Log("Please provide a service name.", NotifyType.ErrorMessage); //return; } else { bool returnNow = false; if (string.IsNullOrEmpty(RemoteSocketListenerSvrName)) //(String.IsNullOrEmpty(ServiceNameForConnect)) { Sox.Instance.Log("Please provide a server name.", NotifyType.ErrorMessage); //return; returnNow = true; } // 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. else { try { hostName = new HostName(RemoteSocketListenerSvrName);// HostNameForConnect.Text); } catch (TaskCanceledException) { Sox.Instance.Log("Canceled.", NotifyType.StatusMessage); } catch (ArgumentException) { Sox.Instance.Log("Error: Invalid host name.", NotifyType.ErrorMessage); //return; returnNow = true; } } if (!returnNow) { StreamSocket socket = new StreamSocket(); // If necessary, tweak the socket's control options before carrying out the connect operation. // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options. socket.Control.KeepAlive = false; try { if (adapter == null) { Sox.Instance.Log("Connecting to: " + hostName.DisplayName, NotifyType.StatusMessage); Sox.Instance.Log("On Port: " + PortOrServicenameForListener, NotifyType.StatusMessage); Sox.StartToken(); // Connect to the server (by default, the listener we created in the previous step). await socket.ConnectAsync(hostName, PortOrServicenameForListener).AsTask(Sox.CancelToken); Sox.Instance.Log("Connected", NotifyType.StatusMessage); CoreApplication.Properties.Add("clientSocket", socket); } else { Sox.Instance.Log( "Connecting to: " + RemoteSocketListenerSvrName + " using network adapter " + adapter.NetworkAdapterId, NotifyType.StatusMessage); // Connect to the server (by default, the listener we created in the previous step) // limiting traffic to the same adapter that the user specified in the previous step. // This option will be overridden by interfaces with weak-host or forwarding modes enabled. Sox.StartToken(); await socket.ConnectAsync( hostName, PortOrServicenameForListener,// ServiceNameForConnect.Text, SocketProtectionLevel.PlainSocket, adapter).AsTask(Sox.CancelToken); // Save the socket, so subsequent steps can use it. Sox.Instance.Log( "Connected using network adapter " + adapter.NetworkAdapterId, NotifyType.StatusMessage); } // Mark the socket as connected. Set the value to null, as we care only about the fact that the // property is set. CoreApplication.Properties.Add("connected", null); } catch (TaskCanceledException) { if (CoreApplication.Properties.ContainsKey("connected")) { CoreApplication.Properties.Remove("connected"); } Sox.AppMode = AppMode.NewClient; Sox.Instance.Log("Cancelled.", NotifyType.StatusMessage); } catch (Exception exception) { if (CoreApplication.Properties.ContainsKey("connected")) { CoreApplication.Properties.Remove("connected"); } Sox.AppMode = AppMode.NewClient; // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } Sox.Instance.Log("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } } } } } }
private async void OnConnection( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } uint sizeFieldCount1 = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount1 != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint msgtype = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. if (msgtype == 1) { reader.ReadBytes(readByte); } else if (msgtype == 2) { stringtemp = reader.ReadString(actualStringLength); } else if (msgtype == 3) { receiverbuf = reader.ReadBuffer(actualStringLength); receive_buf_flag = 1; } } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } stringtemp = "Read stream failed with error: " + exception.Message; } }
/// <summary> /// Invoked once a connection is accepted by Listen() or /// a connection has been establed by Connect(). /// <param name="sender">The listener that accepted the connection.</param> /// <param name="args">Parameters associated with the accepted connection.</param> /// <param name="activeListeningID">The ID associated with the <see cref="activeListenerIDs"/> dict</param> /// <param name="numAttempts">The number of times listening for messages has already been tried</param> /// </summary> private async void ListenForMessages( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args, int activeListeningID, int numAttempts = 0) { PrintLine(); // check the number of attempts made if (numAttempts >= MAX_LISTEN_ATTEMPTS) { var e = new TimeoutException("Too many attempts to listen for messages from remote server"); FatalException(this, new FatalEventArgs( ExceptionType.CONNECTION_NOT_ESTABLISHED, e)); return; } // check that the reader exists if (_dataReader == null) { var e = new NullReferenceException("reader doesn't exist for socket"); FatalException(this, new FatalEventArgs( ExceptionType.RECEIVE_FAILED, e)); return; } try { // send alignment message string alignmentMessage = INIT_MESSAGE + INIT_MESSAGE + INIT_MESSAGE + INIT_MESSAGE_END; _dataWriter.WriteBytes(Encoding.UTF8.GetBytes(alignmentMessage)); await _dataWriter.StoreAsync(); // makes sure bytes are properly aligned await AlignIncomingMessages(); // continue listening for incoming messages for forever! while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await _dataReader.LoadAsync(sizeof(uint)); //System.Diagnostics.Debug.WriteLine(sizeFieldCount); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. SocketClosed(this, new SocketClosedEventArgs(this)); return; } // Read the string. byte[] stringLengthBytes = new byte[sizeof(uint)]; _dataReader.ReadBytes(stringLengthBytes); uint stringLength = BitConverter.ToUInt32(stringLengthBytes, 0); uint actualStringLength = await _dataReader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. SocketClosed(this, new SocketClosedEventArgs(this)); return; } // retrieve and parse the message int byteCount = Encoding.UTF8.GetBytes(new String((char)1, (int)stringLength)).Length; byte[] messageBytes = new byte[byteCount]; _dataReader.ReadBytes(messageBytes); string m = Encoding.UTF8.GetString(messageBytes, 0, byteCount); // Tell the main program that a message has been received, and what that message is if (MessageReceived != null) { System.Diagnostics.Debug.WriteLine(String.Format("<< {0} [{1}]", m, numAttempts)); MessageReceived(this, new MessageReceivedEventArgs(m)); } } } catch (Exception e) { // check if I should stop listening if (activeListenerIDs[activeListeningID] == false) { return; } if (e.Message == CONNECTION_CLOSED_REMOTELY || e is NullReferenceException) { // close the socket Close(); SocketClosed(this, new SocketClosedEventArgs(this)); NonFatalException(this, new FatalEventArgs( ExceptionType.RECEIVE_FAILED, e)); return; } else if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown) { // If this is an unknown status it means that the error is fatal and retry will likely fail. FatalException(this, new FatalEventArgs( ExceptionType.RECEIVE_FAILED, e)); return; } else { NonFatalException(this, new NonFatalEventArgs( ExceptionType.RECEIVE_FAILED, e)); // attempt to continue listening ListenForMessages(sender, args, activeListeningID, numAttempts + 1); } } }