private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error: Could not get socket"); Disconnect(); return; } bluetoothDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); System.Diagnostics.Debug.WriteLine("Connected to Client"); isConnected = true; OnConnected(); mainLoop(); }
private async void OnConnectionReceived(StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { // provider.StopAdvertising(); // isAdvertising = false; // provider = null; // listener.Dispose(); try { socket = args.Socket; writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); inStream = socket.InputStream.AsStreamForRead(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; Debug.WriteLine("Connection device."); var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); naame = remoteDevice.Name; DateTime dateTime = new DateTime(); dateTime = DateTime.Now; await Text.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Text.Text += dateTime.ToString() + ">>" + ">>Connection device: " + remoteDevice.Name + "\n"; }); Debug.WriteLine("Connection device." + remoteDevice.Name); Debug.WriteLine("Connection established."); listeningTask = new Task(() => StartListeringBute()); listeningTask.Start(); } catch (Exception) { } // Notify connection received. }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StreamSocket btStreamSocket; try { btStreamSocket = args.Socket; } catch (Exception ex) { /*await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => * { * rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage); * }); * Disconnect();*/ throw new Exception("新しいデバイスが見つかりましたが、Socketの取得に失敗しました。", ex); } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(btStreamSocket.Information.RemoteHostName); var writer = new DataWriter(btStreamSocket.OutputStream); var reader = new DataReader(btStreamSocket.InputStream); var btReaderWriter = new BTReaderWriter(reader, writer); btReaderWriters.Add(btReaderWriter); //await SendMessage(new Scene(Scene.Scenes.Arabian, 0)); }
GetRfcommDeviceServiceForHostFromUuid(HostName host, Guid uuid) { RfcommServiceId id; BluetoothDevice device; id = RfcommServiceId.FromUuid(uuid); device = await BluetoothDevice.FromHostNameAsync(host); return((await device.GetRfcommServicesForIdAsync(id)).Services[0]); }
private async void RfcommServiceProviderSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StreamSocket socket = args.Socket; var remoteWin10Device = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); var remoteDevice = (BluetoothManager as BluetoothManager).GetBluetoothDeviceFromDeviceInformation(remoteWin10Device.DeviceInformation); System.Diagnostics.Debug.WriteLine("SOME ONE CONNECT:" + remoteWin10Device.DeviceInformation.Id); var connection = new RXRFCommConnection(this, remoteDevice, socket); RfcommConnectionList.Add(connection); connection.Disposed += Connection_Disposed; OnConnectionReceived?.Invoke(this, connection); }
private async void OnConnectionReceivedAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { m_socket = args.Socket; var remoteDevice = await BluetoothDevice.FromHostNameAsync(m_socket.Information.RemoteHostName); m_messageOutstream = new DataWriter(m_socket.OutputStream); m_messageInStream = new DataReader(m_socket.InputStream); var readSuccess = false; do { readSuccess = await OnMessageReceived(); } while (readSuccess); }
private async void RecieveConnection(StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { Console.WriteLine("Connection Received from: " + listener.Information); try { socket = args.Socket; var device = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); var connectedDevice = new ConnectedDevice(device.Name, device, writer, reader, netctl); netctl.AddDevice(connectedDevice); Logging.Log.Trace("Connected to Client: " + device.Name); } catch (Exception e) { Console.WriteLine("Error while creating socket: " + e.Message); } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { this.Logger.Info("クライアント接続"); try { Socket = args.Socket; var rmtdev = await BluetoothDevice.FromHostNameAsync(Socket.Information.RemoteHostName); SocketWriter = new DataWriter(Socket.OutputStream); SocketReader = new DataReader(Socket.InputStream); AcceptingFlag = true; this.ReceiveTask = Task.Run(() => { this.RunReceive(); }); this.SendTask = Task.Run(() => { this.RunSend(); }); this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Connect)); } catch (Exception ex) { this.RunningFlag = false; this.Logger.Error(ex, "クライアント接続中にエラー発生!"); this.Logger.Error(ex.ToString()); } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (socket != null) { Stop(false); } if (socketListener == null) { Stop(true); return; } socket = args.Socket; var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); BeginInvoke(new MethodInvoker(() => { status.Text = $"Connected to {remoteDevice.Name}."; sendButton.Enabled = true; })); await ReadAsync(socket.InputStream).ConfigureAwait(true); }
/// <summary> /// StreamSocketを受け取ったら呼ばれるコールバック /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // もうリスナーは必要ない socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { Disconnect(); Console.WriteLine(e.Message); return; } // 指定されたソケットからBluetoothデバイスを取得するためのサポートされている方法 var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); writer.UnicodeEncoding = UnicodeEncoding.Utf8; reader = new DataReader(socket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; //reader.ByteOrder = ByteOrder.LittleEndian; bool remoteDisconnection = false; await Dispatcher.BeginInvoke( new Action(() => { }) ); try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); //uint bytesToRead = reader.ReadUInt32(); //Console.WriteLine(reader.ReadString(bytesToRead)+"aaaaaaaaaaa"); //シグナルを送る操作 if (readLength == 4 && connectflag == 1) { await Dispatcher.BeginInvoke( new Action(() => { RecordPoints.IsChecked = true; }) ); readLength = 0; //break; StopWatch.Start(); recordflag = 1; byte[] data = System.Text.Encoding.UTF8.GetBytes("シグナル"); writer.WriteBytes(data); await writer.StoreAsync(); Disconnect(); } } catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await Dispatcher.BeginInvoke( new Action(() => { }) ); } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.BeginInvoke( new Action(() => { }) ); } }
private async void OnControllerDataReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore _controllerSocketListener.Dispose(); _controllerSocketListener = null; try { _socket = args.Socket; } catch (Exception e) { Debugger.Break(); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(_socket.Information.RemoteHostName); _writer = new DataWriter(_socket.OutputStream); var reader = new DataReader(_socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ControTextBlock.Text = "连接到" + remoteDevice.Name; }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); float.Parse(message.Substring(0, 5)); float.Parse(message.Substring(5, 5)); float.Parse(message.Substring(10, 5)); //改变视角,message[0]至message[4]为Pitch,message[5]至message[9]为Roll,message[10]至message[14]为Yaw } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ControTextBlock.Text = "已断开连接"; }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ControTextBlock.Text = "未连接"; }); } }
async private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { socket = args.Socket; var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); Console.WriteLine("connection recieved"); while (true) { try { var reader = new DataReader(socket.InputStream); var writer = new DataWriter(socket.OutputStream); // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { //disconnected early break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); string message = reader.ReadString(currentLength); Console.WriteLine(message); writer.WriteString(message); await writer.StoreAsync(); Console.WriteLine("written"); await reader.LoadAsync(sizeof(uint)); int response = reader.ReadInt32(); Console.WriteLine("after await"); if (response == 1) { //success write_first_time_settings(message); break; } else { //failure, app will try again, go through loop again Console.WriteLine("error"); continue; } } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage); //}); //break; } } //if (remoteDisconnection) //{ // Disconnect(); // await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => // { // rootPage.NotifyUser("Client disconnected", NotifyType.StatusMessage); // }); //} }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Debug.WriteLine("Connection received"); try { socket = args.Socket; } catch (Exception e) { Debug.Write(e); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; Debug.Write("Connected to Client: " + remoteDevice.Name); var value = lightPin.Read(); if (value == GpioPinValue.High) { SendMessage($"Hi! Light is curently on!"); } else { SendMessage($"Hi! Light is curently off!"); } // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } var currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); if (message.Equals("on", StringComparison.CurrentCultureIgnoreCase)) { lightPin.Write(GpioPinValue.High); } else if (message.Equals("off", StringComparison.CurrentCultureIgnoreCase)) { lightPin.Write(GpioPinValue.Low); } Debug.Write("Received: " + message); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { Debug.Write("Client Disconnected Successfully"); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); Debug.Write("Client disconnected"); } }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Status.Text = e.Message; }); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); var remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Status.Text = "Connected to Client: " + remoteDevice.Name; }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { switch (message) { case ("Walking"): mediaElement.Pause(); mediaElement.Play(); mediaElement.PlaybackRate = 1.0; break; case ("Running"): mediaElement.Pause(); mediaElement.Play(); mediaElement.PlaybackRate = 1.5; break; case ("Stationary"): mediaElement.Pause(); break; default: mediaElement.Pause(); break; } Status.Text = "Activity: " + message + "PlaybackRate= " + mediaElement.PlaybackRate; }); } catch (Exception ex) { Status.Text = ex.Message + "Remote Disconnection: " + remoteDisconnection; } } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Debug.WriteLine(e.Message); }); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Debug.WriteLine("Connected to Client: " + remoteDevice.Name); SendMessage("IOTCore Master App:"); }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { Debug.WriteLine("Received: " + message); if (message.ToUpper() == "?") { SendMessage("GETWLAN"); SendMessage("GETCURRENTNET"); SendMessage("CONNECTWLANPW,[SSID],[PASSWORD]"); } else if (message.ToUpper() == "GETWLAN") { NetworkPresenter np = new NetworkPresenter(); await Task.Delay(100); var networklist = await np.GetAvailableNetworks(); foreach (WiFiAvailableNetwork network in networklist) { SendMessage("WLAN,NETINFO," + network.Ssid + "," + network.SecuritySettings.NetworkAuthenticationType.ToString()); } } else if (message.ToUpper() == "GETCURRENTNET") { NetworkPresenter np = new NetworkPresenter(); await Task.Delay(100); var networklist = await np.GetAvailableNetworks(); WiFiAvailableNetwork network = np.GetCurrentWifiNetwork(); if (network != null) { SendMessage("WLAN,CURRENTNET,CONNECTED," + network.Ssid + "," + network.SecuritySettings.NetworkAuthenticationType.ToString() + ',' + NetworkPresenter.GetCurrentIpv4Address()); } else { SendMessage("WLAN,CURRENTNET,DISCONNECTED"); } } else if (message.ToUpper().Contains("CONNECTWLANPW")) { string[] s = message.Split(','); try { string net = s[1]; string password = s[2]; WiFiAvailableNetwork connectnetwork = null; NetworkPresenter np = new NetworkPresenter(); await Task.Delay(100); var networklist = await np.GetAvailableNetworks(); foreach (WiFiAvailableNetwork network in networklist) { if (network.Ssid == net) { connectnetwork = network; break; } } if (connectnetwork == null) { SendMessage("CONNECTWLANPW,ERROR,UNKNOWNSSID"); } else { PasswordCredential credential = new PasswordCredential(); credential.Password = password; bool result = await np.ConnectToNetworkWithPassword(connectnetwork, true, credential); } } catch { SendMessage("ERROR,COMMAND,SYNTAXERROR"); } } else { SendMessage("ERROR,COMMAND,UNKNOWN"); } }); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Debug.WriteLine("Client Disconnected Successfully"); }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Debug.WriteLine("Client disconnected"); }); } }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Debug.WriteLine("Connection received"); //if (this.isVoiceModeActive) //{ // Debug.Write("Voice Mode Active!"); // this.SendMessage("Disconnecting device. Aucovei voice mode active."); // return; //} try { this.socket = args.Socket; } catch (Exception e) { Debug.Write(e); this.Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(this.socket.Information.RemoteHostName); var notifyEventArgs = new NotifyUIEventArgs() { NotificationType = NotificationType.ControlMode, Name = "Bluetooth", Data = remoteDevice.Name }; this.NotifyUIEvent(notifyEventArgs); this.writer = new DataWriter(this.socket.OutputStream); var reader = new DataReader(this.socket.InputStream); var remoteDisconnection = false; this.playbackService.PlaySoundFromFile(PlaybackService.SoundFiles.Default); Debug.Write("Connected to Client: " + remoteDevice.Name); this.SendMessage("hostip:" + Helper.Helpers.GetIPAddress()); await Task.Delay(500); this.SendMessage("Ready!"); // Set speed to normal await this.commandProcessor.ExecuteCommandAsync(Commands.SpeedNormal); this.displayManager.ClearRow(1); this.displayManager.AppendImage(DisplayImages.BluetoothFind2, 0, 1); this.displayManager.AppendText(" " + remoteDevice.Name, 20, 1); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message var readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the displayName is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } var currentLength = reader.ReadUInt32(); if (currentLength == 0) { return; } // Load the rest of the message since you already know the length of the displayName expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the displayName is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } var message = reader.ReadString(currentLength); notifyEventArgs = new NotifyUIEventArgs() { NotificationType = NotificationType.Console, Data = message }; this.NotifyUIEvent(notifyEventArgs); await this.commandProcessor.ExecuteCommandAsync(message); Debug.Write("Received: " + message); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { Debug.Write("Client Disconnected Successfully"); break; } } reader.DetachStream(); if (remoteDisconnection) { this.Disconnect(); Debug.Write("Client disconnected"); } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBox_log.Text += string.Format("OnConnectionReceived : Exception occured : {0}\n", e.Message); }); Disconnect(); return; } var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBox_log.Text += string.Format("Connected to Client : {0}\n", remoteDevice.Name); }); string buffer = ""; while (true) { try { uint readLength = await reader.LoadAsync(1); if (readLength < 1) { remoteDisconnection = true; break; } string dat = reader.ReadString(1); if ("\n" == dat) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBox_log.Text += string.Format("Received : {0} : {1}\n", remoteDevice.Name, buffer); }); buffer = ""; } else { buffer += dat; } } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBox_log.Text += ("Client Disconnected Successfully\n"); }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { TextBox_log.Text += ("Client disconnected\n"); }); } }
/// <summary> /// Starts the data reader on the socket to start reading any incoming messages /// </summary> /// <param name="socket"></param> private async void StartReader(StreamSocket socket) { try { _socket = socket; } catch (Exception e) { App.LogService.Write(e.Message, Windows.Foundation.Diagnostics.LoggingLevel.Error); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); _writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; NotifyMessageReceived($"{remoteDevice.Name} has connected"); App.LogService.Write("Connected to Client: " + remoteDevice.Name); App.LogService.Write("Starting data reader..."); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); App.LogService.Write("Current Length: " + currentLength); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); App.LogService.Write("Read Length: " + currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); NotifyMessageReceived($"{remoteDevice.Name}: {message}"); App.LogService.Write("Received: " + message); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { App.LogService.Write("Client Disconnected Successfully"); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); App.LogService.Write("Client disconnected"); } }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception) { Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; // TODO: notify connected //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage); //}); // Infinite read buffer loop while (true) { try { uint size = await reader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { remoteDisconnection = true; return; } var type = DataHandler.RecognizeDataType(reader); switch (type) { case DataHandlerTypes.ByteArray: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadByteArrayAsync(reader), typeof(byte[]))); break; case DataHandlerTypes.Int32: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadInt32Async(reader), typeof(Int32))); break; case DataHandlerTypes.String: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadStringAsync(reader), typeof(string))); break; case DataHandlerTypes.IBuffer: DataReceived?.Invoke(this, new DataReceivedEventArgs(await DataHandler.ReadIBufferAsync(reader), typeof(IBuffer))); break; } } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { // Client Disconnected Successfully break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); // Client Disconnected Successfully } }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { status.Text = string.Format("{0}: {1}", MainPage.NotifyType.ErrorMessage, e.Message); //MP.NotifyUser(e.Message, NotifyType.ErrorMessage); }); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //MP.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage); status.Text = string.Format("{0}: {1}", MainPage.NotifyType.StatusMessage, "Connected to Client: "); }); _Mode = Mode.JustConnected; // Infinite read buffer loop recvdtxt = ""; while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await ReadAsync(message); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ConversationListBox.Items.Insert(0, "Received: " + message); }); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //MP.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage); status.Text = string.Format("{0}: {1}", MainPage.NotifyType.StatusMessage, "Client Disconnected Successfully"); }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //MP.NotifyUser("Client disconnected", NotifyType.StatusMessage); status.Text = string.Format("{0}: {1}", MainPage.NotifyType.StatusMessage, "Client disconnected"); ListenButton_Click(null, null); }); } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { Disconnect(); //HoloLensのSetting -> Privacy -> Other Device -> Use Trusted Devices -> Let these apps use my [Device Name] を確認 return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; //("Connected to Client:" + remoteDevice.Name); isConnectedBluetooth = true; state = "Connected "; //SendMessage("Test"); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); //string message = reader.ReadString(1); //readLength = 12; // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } string tmp = reader.ReadString(4); uint currentLength = Convert.ToUInt32(tmp); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); //await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); //string message = reader.ReadString(1); //("Recieved : "+message); messageBuffer = message; isChangedMessage = true; } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { //Client Disconnected Successfully... state = "None"; break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); //Client disconnected } }
/// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore _socketListener.Dispose(); _socketListener = null; try { _socket = args.Socket; } catch (Exception e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Console.WriteLine("ERROR: " + e.Message); }); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(_socket.Information.RemoteHostName); _writer = new DataWriter(_socket.OutputStream); var reader = new DataReader(_socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Console.WriteLine("NOTICE: Connected to Client " + remoteDevice.Name); }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ConversationListBox.Items.Add("Received: " + message); }); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Console.WriteLine("STATUS: Client Disconnected Successfully"); }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Console.WriteLine("STATUS: Client disconnected"); }); } }
private async void OnConnectionReceivedAsync( StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { // Stop advertising/listening so that we're only serving one client _provider.StopAdvertising(); listener.Dispose(); listener = null; _socket = args.Socket; // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(_socket.Information.RemoteHostName); _writer = new DataWriter(_socket.OutputStream); var reader = new DataReader(_socket.InputStream); bool remoteDisconnection = false; Debug.WriteLine("Connected to Client: " + remoteDevice.Name); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); var parameter = JsonConvert.DeserializeObject <RemoteParameter>(message); string serializedData = await CommandReceived(parameter); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when((uint)ex.HResult == 0x800703E3) { Debug.WriteLine("Client Disconnected Successfully"); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); Debug.WriteLine("Client disconnected"); } }