private async void Button_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect(200, 20, 50, 50)); if (dev != null) { // if a device is selected create a BluetoothDevice instance to get more information RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id); if (service != null) { foreach (KeyValuePair <uint, IBuffer> attrib in await service.GetSdpRawAttributesAsync()) { SdpDataElement de = SdpDataElement.FromByteArray(attrib.Value.ToArray()); System.Diagnostics.Debug.WriteLine(attrib.Key.ToString("X") + " " + de.ToString()); } // set data-binding so that device properties are displayed DeviceInformationPanel.DataContext = service; } } }
public async Task <String> GetNameAttribute(RfcommDeviceService service) { try { var attributes = await service.GetSdpRawAttributesAsync(BluetoothCacheMode.Uncached); if (!attributes.ContainsKey(SERVICE_NAME_ATTRIBUTE_ID)) { System.Diagnostics.Debug.WriteLine("Name attribute not found"); return(""); } var attributeReader = DataReader.FromBuffer(attributes[SERVICE_NAME_ATTRIBUTE_ID]); var attributeType = attributeReader.ReadByte(); if (attributeType != SERVICE_NAME_ATTRIBUTE_TYPE) { System.Diagnostics.Debug.WriteLine("Name attribute type not right :" + attributeType + " , expecting : " + SERVICE_NAME_ATTRIBUTE_TYPE); return(""); } var nameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; return(attributeReader.ReadString(nameLength)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("GetNameAttribute - Exception " + ex.Message); } return(""); }
bool IsCompatibleVersion(RfcommDeviceService service) { var attributes = service.GetSdpRawAttributesAsync(BluetoothCacheMode.Uncached).GetResults(); var attribute = attributes[SERVICE_VERSION_ATTRIBUTE_ID]; var reader = DataReader.FromBuffer(attribute); // The first byte contains the attribute' s type byte attributeType = reader.ReadByte(); if (attributeType == SERVICE_VERSION_ATTRIBUTE_TYPE) { // The remainder is the data uint version = reader.ReadUInt32(); //.Uint32(); return(version >= MINIMUM_SERVICE_VERSION); } return(false); }
private async Task GetListSDPAttributes(RfcommDeviceService service) { // Sample output. See: https://www.bluetooth.com/specifications/assigned-numbers/service-discovery/ //SDP Attribute id | Capacity | Length | Description(?) // 256 7 7 // 0 5 5 // 6 11 11 // 4 14 14 // 1 5 5 (service class ID list try { // TODO get extra info on attributes - ServiceDiscoveryProtocol var sdpAttr = await service.GetSdpRawAttributesAsync(BluetoothCacheMode.Uncached); foreach (var attr in sdpAttr) { this.log.Info("HarvestInfo", () => string.Format(" SDP Attribute:{0} (0x{0:X}) Capacity:{1} Length:{2}", attr.Key, attr.Value.Capacity, attr.Value.Length)); } } catch (Exception e) { this.log.Exception(9999, "", e); } }
public async void Connect(string devid) { this.Logger.Info("入力デバイスへの接続開始:" + devid); this.StartingSendTaskFlag = true; this.StartingReceiveTaskFlag = true; this.SelectedDeviceInfo = (from i in KnownDeviceList where i.Id == devid select i).First(); try { SelectedDevice = await BluetoothDevice.FromIdAsync(this.SelectedDeviceInfo.Id); var rfcommsrv = await SelectedDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceUuid), BluetoothCacheMode.Uncached); RfcommService = rfcommsrv.Services[0]; var attributes = await RfcommService.GetSdpRawAttributesAsync(); var attributereader = DataReader.FromBuffer(attributes[0x100]); var attributetype = attributereader.ReadByte(); var servicenamelength = attributereader.ReadByte(); attributereader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16BE; Socket = new StreamSocket(); await Socket.ConnectAsync(RfcommService.ConnectionHostName, RfcommService.ConnectionServiceName); SocketWriter = new DataWriter(Socket.OutputStream); SocketReader = new DataReader(Socket.InputStream); this.RunningFlag = true; this.SendTask = Task.Run(() => { this.RunSend(); }); this.ReceiveTask = Task.Run(() => { this.RunReceive(); }); this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Connect)); } catch (Exception ex) { this.Logger.Error(ex, "入力デバイスへの接続失敗"); this.RunningFlag = false; this.StartingSendTaskFlag = false; this.StartingReceiveTaskFlag = false; this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Error)); } }
// This App relies on CRC32 checking available in version 2.0 of the service. //const uint SERVICE_VERSION_ATTRIBUTE_ID = 0x0300; //const byte SERVICE_VERSION_ATTRIBUTE_TYPE = 0x0A; // UINT32 //const uint MINIMUM_SERVICE_VERSION = 200; private async Task <bool> IsCompatibleVersion(RfcommDeviceService service) { try { var attributes = await service.GetSdpRawAttributesAsync( //BluetoothCacheMode.Cached); BluetoothCacheMode.Uncached); if (attributes != null) { var lst = attributes.Keys.ToList <uint>(); if (attributes.Keys.Contains(Constants.SERVICE_VERSION_ATTRIBUTE_ID)) { var attribute = attributes[Constants.SERVICE_VERSION_ATTRIBUTE_ID]; var reader = DataReader.FromBuffer(attribute); // The first byte contains the attribute' s type byte attributeType = reader.ReadByte(); if (attributeType == Constants.SERVICE_VERSION_ATTRIBUTE_TYPE) { // The remainder is the data uint version = reader.ReadUInt32(); return(version >= Constants.MINIMUM_SERVICE_VERSION); } } else { PostMessage("OBEX_Sender.IsCompatibleVersion", string.Format("Service Attribute Count: {0}", attributes.Count())); PostMessage("OBEX_Sender.IsCompatibleVersion", "SERVICE_VERSION_ATTRIBUTE_ID not in Service Attributes"); } } } catch (Exception ex) { PostMessage("OBEX_Sender.IsCompatibleVersion", ex.Message); } return(false); }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, we will automatically attempt to connect to the /// chat service of the selected device. If the connection succeeds, we will automatically stream /// the messages from the connected deviced. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void DeviceList_Tapped(object sender, TappedRoutedEventArgs e) { StartButton.IsEnabled = false; //Get chat service from the selected device. var chatServiceDevice = chatServiceDeviceCollection[DeviceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceDevice.Id); NotifyUser("Connecting ...", NotifyType.StatusMessage); if (chatService == null) { NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); StartButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); StartButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; string ServiceName = attributeReader.ReadString(serviceNameLength); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); NotifyUser("Connected to chat service \"" + ServiceName + "\".", NotifyType.StatusMessage); ConversationListBox.Items.Add("========== Session Connected =========="); DisconnectButton.IsEnabled = true; ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND default: NotifyUser("Please verify that " + chatServiceDevice.Name + "is running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); StartButton.IsEnabled = true; break; } } }
public async void Connect(RfcommDeviceDisplay deviceInfoDisp) { try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch { //rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call string uuid = "17fcf242-f86d-4e35-805e-" + Constants.BLUETOOTH_ID; Guid RfcommChatServiceUuid = Guid.Parse(uuid); var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { ConnectService = rfcommServices.Services[0]; } else { return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service UInt16 SdpServiceNameAttributeId = 0x100; var attributes = await ConnectService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { Console.WriteLine("sdpAttributeがおかしい"); return; } byte SdpServiceNameAttributeType = (4 << 3) | 5; var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { Console.WriteLine("sdpNameAttributeがおかしい"); return; } var serviceNameLength = attributeReader.ReadByte(); lock (this) //lock構文、排他制御 { ConnectSocket = new StreamSocket(); } try { await ConnectSocket.ConnectAsync(ConnectService.ConnectionHostName, ConnectService.ConnectionServiceName); } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { Console.WriteLine("socket接続がおかしい"); } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async void SelectDevice(int iSelected) { var chatServiceDevice = chatServiceDeviceCollection[iSelected]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceDevice.Id); if (chatService == null) { //rootPage.NotifyUser( // "Access to the device is denied because the application was not granted access", // NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { //rootPage.NotifyUser( // "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + // "Please verify that you are running the BluetoothRfcommChat server.", // NotifyType.ErrorMessage); return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { //rootPage.NotifyUser( // "The Chat service is using an unexpected format for the Service Name attribute. " + // "Please verify that you are running the BluetoothRfcommChat server.", // NotifyType.ErrorMessage); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; //ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); //ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND //rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); //RunButton.IsEnabled = true; break; default: throw; } } }
private async Task SendMessage(string id) { //await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => //{ chatService = await RfcommDeviceService.FromIdAsync(id); if (chatService == null) { statusTextBlock.Text = "Access to the device is denied because the application was not granted access"; return; } //Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { statusTextBlock.Text = @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { statusTextBlock.Text = "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; //ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); await SendMessageAsync(); // Receive Message //DataReader chatReader = new DataReader(chatSocket.InputStream); //ReceiveStringLoop(chatReader); } catch (Exception) { throw; } //}); }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { RunButton.IsEnabled = false; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id); if (chatService == null) { MainPage.Current.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { MainPage.Current.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { MainPage.Current.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { RunButton.IsEnabled = true; MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.ErrorMessage); } }
public async void ConnectAsync(RfcommChatDeviceDisplay deviceInfoDisp) { // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { throw new UnauthorizedAccessException("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch (Exception ex) { throw ex; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { throw new InvalidOperationException("Bluetooth Device returned null. Access Status = " + accessStatus.ToString()); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { throw new InvalidOperationException("Could not discover the chat service on the remote device"); } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { throw new InvalidOperationException("The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."); } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { throw new InvalidOperationException( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."); } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); // TODO: powiadomienie, że połączono //SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveDataLoop(chatReader); } catch (Exception ex) when((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { throw new InvalidOperationException("Please verify that you are running the BluetoothRfcommChat server."); } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { throw new InvalidOperationException("Please verify that there is no other RFCOMM connection to the same device."); } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void DeviceList_Tapped(object sender, TappedRoutedEventArgs e) { RunButton.IsEnabled = false; DeviceList.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceDevice = chatServiceDeviceCollection[DeviceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceDevice.Id); if (chatService == null) { rootPage.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; break; default: throw; } } }
private static async Task<int> ValidateConnection(RfcommDeviceService messageService) { if (messageService == null) { //statusTextBlock.Text = "Access to the device is denied because the application was not granted access"; return -1; } //Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await messageService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { //statusTextBlock.Text = // @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + // "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return -1; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { //statusTextBlock.Text = // "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + // "Please verify that you are running the BluetoothRfcommChat server."; //RunButton.IsEnabled = true; return -1; } return 0; //var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. //attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { ServerButton.IsEnabled = false; ClientButton.IsEnabled = false; DisconnectButton.IsEnabled = true; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; DeviceInformation deviceInfo = await DeviceInformation.CreateFromIdAsync(chatServiceInfo.Id); chatService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id); if (chatService == null) { NotifyStatus("Access to the device is denied because the application was not granted access"); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { NotifyStatus("The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { NotifyStatus("The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Visibility = Visibility.Visible; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { socket = new StreamSocket(); } await socket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); writer = new DataWriter(socket.OutputStream); DataReader chatReader = new DataReader(socket.InputStream); while (true) { try { uint size = await chatReader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data break; } uint stringLength = chatReader.ReadUInt32(); uint actualStringLength = await chatReader.LoadAsync(stringLength); if (actualStringLength != stringLength) { // The underlying socket was closed before we were able to read the whole data break; } ConversationListBox.Items.Add("Received: \"" + chatReader.ReadString(stringLength) + "\""); } catch (Exception ex) { lock (this) { if (socket == null) { // Do not print anything here - the user closed the socket. } else { NotifyStatus("Read stream failed with error: " + ex.Message); Disconnect(); } } } } } catch (Exception ex) { ServerButton.IsEnabled = true; ClientButton.IsEnabled = true; DisconnectButton.IsEnabled = false; NotifyStatus("Error: " + ex.HResult.ToString() + " - " + ex.Message); } }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { RunButton.IsEnabled = false; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id); if (chatService == null) { MainPage.Current.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { MainPage.Current.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { MainPage.Current.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { RunButton.IsEnabled = true; MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.ErrorMessage); } }
public async Task<String> GetNameAttribute(RfcommDeviceService service) { try { var attributes = await service.GetSdpRawAttributesAsync(BluetoothCacheMode.Uncached); if (!attributes.ContainsKey(SERVICE_NAME_ATTRIBUTE_ID)) { System.Diagnostics.Debug.WriteLine("Name attribute not found"); return ""; } var attributeReader = DataReader.FromBuffer(attributes[SERVICE_NAME_ATTRIBUTE_ID]); var attributeType = attributeReader.ReadByte(); if (attributeType != SERVICE_NAME_ATTRIBUTE_TYPE) { System.Diagnostics.Debug.WriteLine("Name attribute type not right :" + attributeType + " , expecting : " + SERVICE_NAME_ATTRIBUTE_TYPE); return ""; } var nameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; return attributeReader.ReadString(nameLength); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("GetNameAttribute - Exception " + ex.Message); } return ""; }
public async void Connect(String devID) { // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. lastDevID = devID; isCanceled = false; isConnected = false; WriteDebug("Check Connection"); DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(devID).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { return; } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(devID); } catch (Exception) { return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { return; } WriteDebug("Sync Devices.."); // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call long start = DateTime.Now.Ticks; RfcommDeviceServicesResult rfcommServices = null; while (true) { rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(guid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { WriteDebug($"{rfcommServices.Error}."); RfService = rfcommServices.Services[0]; break; } lock (this) { long current = DateTime.Now.Ticks; if (current - 10_00000000 > start) { break; } } } if (RfService == null) { isCanceled = true; Disconnect(); onDisconnect(); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await RfService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(0x100)) { return; } var attributeReader = DataReader.FromBuffer(attributes[0x100]); var attributeType = attributeReader.ReadByte(); if (attributeType != ((4 << 3) | 5)) { return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; //------------bind Stream------ lock (this) { streamSocket = new StreamSocket(); } try { await streamSocket.ConnectAsync(RfService.ConnectionHostName, RfService.ConnectionServiceName); WriteDebug($"{RfService.ConnectionHostName} : {RfService.Device.ConnectionStatus}"); dataRegister.conditionText.Text = "Checking Connection..."; dataWriter = new DataWriter(streamSocket.OutputStream); DataReader chatReader = new DataReader(streamSocket.InputStream); isConnected = true; ReceiveStringLoop(chatReader); } catch (Exception ex) when((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { return; } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { return; } catch { } }
private async Task SendMessage(string id) { chatService = await RfcommDeviceService.FromIdAsync(id); if (chatService == null) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "Access to the device is denied because the application was not granted access"; deferral.Complete(); } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = @"ERROR: The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."; deferral.Complete(); //RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "ERROR: The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."; deferral.Complete(); //RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. //attributeReader.UnicodeEncoding = System.Text.UnicodeEncoding.Utf8; lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); await SendMessageAsync(); // Receive Message //DataReader chatReader = new DataReader(chatSocket.InputStream); //ReceiveStringLoop(chatReader); } catch (Exception ex) { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = ex.ToString(); deferral.Complete(); } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ConnectButton_Click(object sender, RoutedEventArgs e) { // Make sure user has selected a device first if (resultsListView.SelectedItem != null) { rootPage.NotifyUser("Connecting to remote device. Please wait...", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please select an item to connect to", NotifyType.ErrorMessage); return; } RfcommChatDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as RfcommChatDeviceDisplay; // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(deviceInfoDisp.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { rootPage.NotifyUser("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices", NotifyType.ErrorMessage); return; } // If not, try to get the Bluetooth device try { bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); return; } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (bluetoothDevice == null) { rootPage.NotifyUser("Bluetooth Device returned null. Access Status = " + accessStatus.ToString(), NotifyType.ErrorMessage); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { rootPage.NotifyUser( "Could not discover the chat service on the remote device", NotifyType.StatusMessage); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { rootPage.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { rootPage.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; deviceWatcher.Stop(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); SetChatUI(attributeReader.ReadString(serviceNameLength), bluetoothDevice.Name); chatWriter = new DataWriter(chatSocket.OutputStream); DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND rootPage.NotifyUser("Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); RunButton.IsEnabled = true; break; default: throw; } } }
/// <summary> /// Invoked once the user has selected the device to connect to. /// Once the user has selected the device, /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async Task <bool> ConnectAsync(RomeRemoteSystem system) { // Make sure user has selected a device first if (system != null) { Debug.WriteLine("Connecting to remote device. Please wait..."); } else { Debug.WriteLine("Please select an item to connect to"); return(false); } // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(system.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { Debug.WriteLine("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); return(false); } // If not, try to get the Bluetooth device try { _bluetoothDevice = await BluetoothDevice.FromIdAsync(system.Id); } catch (Exception ex) { Debug.WriteLine(ex.Message); StopWatcher(); return(false); } // If we were unable to get a valid Bluetooth device object, // it's most likely because the user has specified that all unpaired devices // should not be interacted with. if (_bluetoothDevice == null) { Debug.WriteLine("Bluetooth Device returned null. Access Status = " + accessStatus.ToString()); } if (_bluetoothDevice == null) { return(false); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await _bluetoothDevice?.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.SERVICE_UUID), BluetoothCacheMode.Uncached); if (rfcommServices?.Services.Count > 0) { _chatService = rfcommServices.Services[0]; } else { Debug.WriteLine("Could not discover the chat service on the remote device"); StopWatcher(); return(false); } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await _chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SERVICE_ATTRIBUTE_ID)) { Debug.WriteLine( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."); StopWatcher(); return(false); } var attributeReader = DataReader.FromBuffer(attributes[Constants.SERVICE_ATTRIBUTE_ID]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SERVICE_ATTRIBUTE_TYPE) { Debug.WriteLine( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."); StopWatcher(); return(false); } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; StopWatcher(); lock (this) { _chatSocket = new StreamSocket(); } try { await _chatSocket.ConnectAsync(_chatService.ConnectionHostName, _chatService.ConnectionServiceName); Debug.WriteLine("Connected to : " + attributeReader.ReadString(serviceNameLength) + _bluetoothDevice.Name); _chatWriter = new DataWriter(_chatSocket.OutputStream); DataReader chatReader = new DataReader(_chatSocket.InputStream); ReceiveStringLoop(chatReader); return(true); } catch (Exception ex) when((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { Debug.WriteLine("Please verify that you are running the BluetoothRfcommChat server."); StopWatcher(); } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { Debug.WriteLine("Please verify that there is no other RFCOMM connection to the same device."); StopWatcher(); } return(false); }
private async void Connect(DeviceInformation devInfo) { // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. DeviceAccessStatus accessStatus = DeviceAccessInformation.CreateFromId(devInfo.Id).CurrentStatus; if (accessStatus != DeviceAccessStatus.Allowed) { System.Diagnostics.Debug.WriteLine("Access State: " + accessStatus); System.Diagnostics.Debug.WriteLine("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); //return; } // TODO: Maybe automatic pairing? try { bluetoothDevice = await BluetoothDevice.FromIdAsync(devInfo.Id); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error: Couldn't get BluetoothDevice"); return; } if (bluetoothDevice == null) { System.Diagnostics.Debug.WriteLine("Bluetooth Device returned null. Access Status = " + accessStatus.ToString()); } // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid), BluetoothCacheMode.Uncached); // Maybe change to cached??? if (rfcommServices.Services.Count > 0) { service = rfcommServices.Services[0]; } else { System.Diagnostics.Debug.WriteLine("Error: Could not discover the chat service on the remote device"); System.Diagnostics.Debug.WriteLine("Paired: " + devInfo.Pairing.IsPaired); System.Diagnostics.Debug.WriteLine("Connection Status: " + bluetoothDevice.ConnectionStatus); return; } // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service var attributes = await service.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(Constants.SdpServiceNameAttributeId)) { System.Diagnostics.Debug.WriteLine( "The service is not advertising the Service Name attribute (attribute id=0x100)."); return; } var attributeReader = DataReader.FromBuffer(attributes[Constants.SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != Constants.SdpServiceNameAttributeType) { System.Diagnostics.Debug.WriteLine( "The Chat service is using an unexpected format for the Service Name attribute. "); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; StopWatcher(); lock (this) { socket = new StreamSocket(); } try { await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName); writer = new DataWriter(socket.OutputStream); reader = new DataReader(socket.InputStream); System.Diagnostics.Debug.WriteLine("Connected to Server"); isConnected = true; OnConnected(); mainLoop(); } catch (Exception ex) when((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { System.Diagnostics.Debug.WriteLine("Please verify that you are running the BluetoothRfcommChat server."); } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { System.Diagnostics.Debug.WriteLine("Please verify that there is no other RFCOMM connection to the same device."); } }
private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { ServerButton.IsEnabled = false; ClientButton.IsEnabled = false; DisconnectButton.IsEnabled = true; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; DeviceInformation deviceInfo = await DeviceInformation.CreateFromIdAsync(chatServiceInfo.Id); chatService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id); if (chatService == null) { NotifyStatus("Access to the device is denied because the application was not granted access"); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { NotifyStatus("The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { NotifyStatus("The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server."); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Visibility = Visibility.Visible; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { socket = new StreamSocket(); } await socket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); writer = new DataWriter(socket.OutputStream); DataReader chatReader = new DataReader(socket.InputStream); while (true) { try { uint size = await chatReader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data break; } uint stringLength = chatReader.ReadUInt32(); uint actualStringLength = await chatReader.LoadAsync(stringLength); if (actualStringLength != stringLength) { // The underlying socket was closed before we were able to read the whole data break; } ConversationListBox.Items.Add("Received: \"" + chatReader.ReadString(stringLength) + "\""); } catch (Exception ex) { lock (this) { if (socket == null) { // Do not print anything here - the user closed the socket. } else { NotifyStatus("Read stream failed with error: " + ex.Message); Disconnect(); } } } } } catch (Exception ex) { ServerButton.IsEnabled = true; ClientButton.IsEnabled = true; DisconnectButton.IsEnabled = false; NotifyStatus("Error: " + ex.HResult.ToString() + " - " + ex.Message); } }