public void Listen(Guid service) { BluetoothListener listener = new BluetoothListener(BluetoothAddress.None, service); listener.Start(10); listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), listener); }
public void ZeroConnections() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); lsnr.Stop(); Assert.IsTrue(ar.IsCompleted, ".IsCompleted"); try { BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); } catch (ObjectDisposedException) { } // Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used all ports"); port0.AssertCloseCalledOnce("acceptor closed"); }
private void acceptBluetoothClient(IAsyncResult ar) { if (client != null) { Stop(false); } if (listener == null) { Stop(true); return; } client = listener.EndAcceptBluetoothClient(ar); stream = client.GetStream(); ReadAsync(stream); Invoke(new MethodInvoker(delegate { status.Text = string.Format("Connected to {0}.", client.RemoteMachineName); sendButton.Enabled = true; })); listener.BeginAcceptBluetoothClient(acceptBluetoothClient, null); }
void Listen() { //BluetoothListener listener = new BluetoothListener(BluetoothAddress.Parse("38:BA:F8:28:32:9F"), BluetoothService.SerialPort); BluetoothListener listener = new BluetoothListener(BluetoothRadio.PrimaryRadio.LocalAddress, BluetoothService.SerialPort); listener.Start(); Console.WriteLine("Listener dziala!"); listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), listener); }
public MainWindow() { InitializeComponent(); getRadios(); listener = new BluetoothListener(chosenRadio.LocalAddress, BluetoothService.SerialPort); listener.Start(10); listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), listener); }
public void OneFailedIncomingConnection() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSink); lsnr.ServiceName = "weeee"; lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately port0.NewEvent(PORT_EV.CONNECT_ERR); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); port0.AssertOpenServerCalledAndClear(29); try { try { BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); } catch (System.IO.IOException ioexShouldNotWrapSEx) { //HACK ioexShouldNotWrapSEx throw ioexShouldNotWrapSEx.InnerException; } Assert.Fail("should have thrown!"); } catch (SocketException) { } TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); // Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); //port0.AssertCloseCalledOnce("first failed connection now closed"); // BluetoothEndPoint lep = lsnr.LocalEndPoint; sdpSvc.AssertCalls( "AddServiceClassIdList: 00001304-0000-1000-8000-00805f9b34fb" + NewLine + "AddRFCommProtocolDescriptor: " + lep.Port + NewLine + "AddServiceName: weeee" + NewLine ); }
private void start_Click(object sender, EventArgs e) { int.TryParse(diastolic.Text, out _diastolicValue); int.TryParse(systolic.Text, out _systolicValue); if (!_serverStarted) { _serverStarted = true; _blueListener.Start(); _blueListener.BeginAcceptBluetoothClient(BluetoothListenerAcceptClientCallback, _blueListener); status.AppendText("\nStarted server...\n"); // PairDevice(); } }
public void OneConnection_PeerImmediatelyCloses() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately FireOpenReceiveCloseEvents firer = new FireOpenReceiveCloseEvents(port0); firer.Run(); //port0.NewEvent(PORT_EV.CONNECTED); //Assert.IsFalse(ar.IsCompleted, "Connect 1 completed"); // 100ms later... firer.Complete(); port0.AssertCloseCalledOnce("first accepted connection now closed"); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); lsnr.Stop(); // //TODO ! Assert.IsTrue(cli.Connected, "cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); // Stream peer = cli.GetStream(); byte[] buf = new byte[10]; int readLen = TestsApmUtils.SafeNoHangRead(peer, buf, 0, buf.Length); Assert.AreEqual(1, readLen, "readLen"); cli.Close(); port0.AssertCloseCalledAtLeastOnce("first accepted connection now closed"); }
public bool Run() { // Returns true if bluetooth starts listening. // Returns false if bluetooth is already running. if (!Running) { Running = true; listener = new BluetoothListener(Guid.Parse("2d26618601fb47c28d9f10b8ec891363")); // Same as in the app listener.Start(); listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), listener); return(true); } return(false); }
private void Start() { try { listener = new BluetoothListener(MyServiceUuid); // Listen on primary radio listener.Start(); listener.BeginAcceptBluetoothClient(acceptBluetoothClient, null); } catch (Exception ex) { MessageBox.Show(this, string.Format("Could not start listener. {0}", ex.Message)); return; } status.Text = string.Format("Listening at {0}, HCI version {1}...", BluetoothRadio.PrimaryRadio.Name, BluetoothRadio.PrimaryRadio.HciVersion); startButton.Enabled = false; stopButton.Enabled = true; }
public void OneConnection() { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); BluetoothFactory.SetFactory(f); TestLsnrRfcommPort port1 = AddSomeCreatablePorts(f); // port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); lsnr.Start(); IAsyncResult ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? port0.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli = lsnr.EndAcceptBluetoothClient(ar); TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); // Assert.IsTrue(cli.Connected, "cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port1.AssertCloseCalledOnce("second acceptor closed"); cli.Close(); port0.AssertCloseCalledOnce("first accepted connection now closed"); // BluetoothEndPoint lep = lsnr.LocalEndPoint; sdpSvc.AssertCalls( "AddServiceClassIdList: 00001303-0000-1000-8000-00805f9b34fb" + NewLine + "AddRFCommProtocolDescriptor: " + lep.Port + NewLine ); }
public static void StartListening() { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; BTListener = new BluetoothListener(_N2FServiceGUID); BTListener.Start(); while (!TerminateAllThreads) { while (Listen) { allDone.Reset(); BTListener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptCallback), BTListener); allDone.WaitOne(); } // sleep for 500ms so when the listener is paused it doesnt munch too much cpu Thread.Sleep(500); } }
public void StartBlueTooth() { try { if (BluetoothRadio.IsSupported) { if (BluetoothRadio.PrimaryRadio.Mode.Equals(RadioMode.PowerOff)) { MessageBox.Show("Bluetooth divice is not enabled."); } else { // BluetoothRadio[] allradios = BluetoothRadio.AllRadios; BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; // foreach (BluetoothRadio br in allradios) { // br.Mode = RadioMode.Discoverable; // } BluetoothEndPoint endPoint = new BluetoothEndPoint(BluetoothRadio.PrimaryRadio.LocalAddress, new Guid("{418b27b0-b144-11e6-9598-0800200c9a66}"), -1); BluetoothListener m_btListener = new BluetoothListener(endPoint); m_btListener.ServiceName = "KaraokeNow Bluetooth Service"; m_btListener.Authenticate = false; m_btListener.Start(10); m_btListener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), m_btListener); } } else { // MessageBox.Show("Bluetooth divice not found."); } } catch (Exception ex) { Logger.LogFile(ex.Message, "", "StartBlueTooth", ex.LineNumber(), "BlueToothConnect"); } }
public override void Start() { listener.Start(); listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptClient), null); }
private void BeginAcceptBluetoothClient() { Console.WriteLine("Listening for BT clients..."); bluetoothListener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), bluetoothListener); }
/// <inheritdoc /> internal override void StartListening(EndPoint desiredLocalListenEndPoint, bool useRandomPortFailOver) { if (IsListening) { throw new InvalidOperationException("Attempted to call StartListening when already listening."); } if (!(desiredLocalListenEndPoint is BluetoothEndPoint)) { throw new ArgumentException("Bluetooth connections can only be made from a local BluetoothEndPoint", "desiredLocalListenIPEndPoint"); } try { ServiceRecordBuilder bldr = new ServiceRecordBuilder(); bldr.AddServiceClass((desiredLocalListenEndPoint as BluetoothEndPoint).Service); if (IsDiscoverable) { bldr.AddCustomAttribute(new ServiceAttribute(NetworkCommsBTAttributeId.NetworkCommsEndPoint, ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 1))); } listenerInstance = new BluetoothListener(desiredLocalListenEndPoint as BluetoothEndPoint, bldr.ServiceRecord); listenerInstance.Start(); listenerInstance.BeginAcceptBluetoothClient(BluetoothConnectionReceivedAsync, null); } catch (SocketException) { //If the port we wanted is not available if (useRandomPortFailOver) { try { Guid service = Guid.NewGuid(); ServiceRecordBuilder bldr = new ServiceRecordBuilder(); bldr.AddServiceClass(service); if (IsDiscoverable) { bldr.AddCustomAttribute(new ServiceAttribute(NetworkCommsBTAttributeId.NetworkCommsEndPoint, ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 1))); } listenerInstance = new BluetoothListener(new BluetoothEndPoint((desiredLocalListenEndPoint as BluetoothEndPoint).Address, service), bldr.ServiceRecord); listenerInstance.Start(); listenerInstance.BeginAcceptBluetoothClient(BluetoothConnectionReceivedAsync, null); } catch (SocketException) { //If we get another socket exception this appears to be a bad IP. We will just ignore this IP if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Error("It was not possible to open a random port on " + desiredLocalListenEndPoint + ". This endPoint may not support listening or possibly try again using a different port."); } throw new CommsSetupShutdownException("It was not possible to open a random port on " + desiredLocalListenEndPoint + ". This endPoint may not support listening or possibly try again using a different port."); } } else { if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Error("It was not possible to listen on " + desiredLocalListenEndPoint.ToString() + ". This endPoint may not support listening or possibly try again using a different port."); } throw new CommsSetupShutdownException("It was not possible to listen on " + desiredLocalListenEndPoint.ToString() + ". This endPoint may not support listening or possibly try again using a different port."); } } this.LocalListenEndPoint = desiredLocalListenEndPoint; this.IsListening = true; }
/// <summary> /// Handle a new incoming bluetooth connection /// </summary> /// <param name="ar"></param> private void BluetoothConnectionReceivedAsync(IAsyncResult ar) { if (!IsListening) { return; } try { var newBTClient = listenerInstance.EndAcceptBluetoothClient(ar); ConnectionInfo newConnectionInfo = new ConnectionInfo(ConnectionType.Bluetooth, newBTClient.Client.RemoteEndPoint, newBTClient.Client.LocalEndPoint, ApplicationLayerProtocol, this); if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Info("New bluetooth connection from " + newConnectionInfo); } NetworkComms.IncomingConnectionEstablishThreadPool.EnqueueItem(QueueItemPriority.Normal, new WaitCallback((obj) => { #region Pickup The New Connection try { BluetoothConnection.GetConnection(newConnectionInfo, ListenerDefaultSendReceiveOptions, newBTClient, true); } catch (ConfirmationTimeoutException) { //If this exception gets thrown its generally just a client closing a connection almost immediately after creation } catch (CommunicationException) { //If this exception gets thrown its generally just a client closing a connection almost immediately after creation } catch (ConnectionSetupException) { //If we are the server end and we did not pick the incoming connection up then tooo bad! } catch (SocketException) { //If this exception gets thrown its generally just a client closing a connection almost immediately after creation } catch (Exception ex) { //For some odd reason SocketExceptions don't always get caught above, so another check if (ex.GetBaseException().GetType() != typeof(SocketException)) { //Can we catch the socketException by looking at the string error text? if (ex.ToString().StartsWith("System.Net.Sockets.SocketException")) { LogTools.LogException(ex, "ConnectionSetupError_SE"); } else { LogTools.LogException(ex, "ConnectionSetupError"); } } } #endregion }), null); } catch (SocketException) { //If this exception gets thrown its generally just a client closing a connection almost immediately after creation } catch (Exception ex) { //For some odd reason SocketExceptions don't always get caught above, so another check if (ex.GetBaseException().GetType() != typeof(SocketException)) { //Can we catch the socketException by looking at the string error text? if (ex.ToString().StartsWith("System.Net.Sockets.SocketException")) { LogTools.LogException(ex, "ConnectionSetupError_SE"); } else { LogTools.LogException(ex, "ConnectionSetupError"); } } } finally { listenerInstance.BeginAcceptBluetoothClient(BluetoothConnectionReceivedAsync, null); } }
void MultipleConnection_(bool auth, bool encrypt, BTM_SEC expectedSecurityLevel) { TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory(); TestLsnrRfCommIf commIf = new TestLsnrRfCommIf(); f.queueIRfCommIf.Enqueue(commIf); TestLsnrRfcommPort port0 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port0); port0.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); BluetoothFactory.SetFactory(f); // BluetoothListener lsnr = new BluetoothListener(BluetoothService.VideoSource); if (auth) { lsnr.Authenticate = true; } if (encrypt) { lsnr.Encrypt = true; } Assert.AreEqual(auth, lsnr.Authenticate, ".Authenticate 1"); Assert.AreEqual(encrypt, lsnr.Encrypt, ".Encrypt 1"); lsnr.Start(); IAsyncResult ar; commIf.AssertSetSecurityLevel(expectedSecurityLevel, true); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port0.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port1 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port1); port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port0.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli0 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port1.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port2 = new TestLsnrRfcommPort(); port2.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); f.queueIRfCommPort.Enqueue(port2); port1.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli1 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port2.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port3 = new TestLsnrRfcommPort(); port3.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); f.queueIRfCommPort.Enqueue(port3); port2.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli2 = lsnr.EndAcceptBluetoothClient(ar); // ar = lsnr.BeginAcceptBluetoothClient(null, null); port3.AssertOpenServerCalledAndClear(29);//adter Start? TestLsnrRfcommPort port4 = new TestLsnrRfcommPort(); f.queueIRfCommPort.Enqueue(port4); port4.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); port3.NewEvent(PORT_EV.CONNECTED); TestsApmUtils.SafeNoHangWaitShort(ar, "Accept"); Assert.IsTrue(ar.IsCompleted, "IsCompleted"); BluetoothClient cli3 = lsnr.EndAcceptBluetoothClient(ar); // TestSdpService2 sdpSvc = f.GetTestSdpService(); Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); lsnr.Stop(); Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls"); Assert.AreEqual(auth, lsnr.Authenticate, ".Authenticate 2"); Assert.AreEqual(encrypt, lsnr.Encrypt, ".Encrypt 2"); // Assert.IsTrue(cli0.Connected, "0 cli.Connected"); Assert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports"); port4.AssertCloseCalledOnce("4 acceptor closed"); cli0.Close(); port0.AssertCloseCalledOnce("0 accepted connection now closed"); // Assert.IsTrue(cli1.Connected, "1 cli.Connected"); cli1.Close(); port1.AssertCloseCalledOnce("1 accepted connection now closed"); // Assert.IsTrue(cli2.Connected, "2 cli.Connected"); cli2.Close(); port2.AssertCloseCalledOnce("2 accepted connection now closed"); // Assert.IsTrue(cli3.Connected, "3 cli.Connected"); cli3.Close(); port3.AssertCloseCalledOnce("3 accepted connection now closed"); }
private async void AcceptConnection(IAsyncResult result) { if (result.IsCompleted) { BluetoothListener m_btListener = (BluetoothListener)result.AsyncState; BluetoothClient remoteDevice = m_btListener.EndAcceptBluetoothClient(result); m_btListener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), m_btListener); m_peerStream = remoteDevice.GetStream(); ClientName = remoteDevice.RemoteMachineName; //keep connection open while (m_listening) { try { string command = null; byte[] buffer = new byte[1024]; int received = 0; received = m_peerStream.Read(buffer, 0, buffer.Length); if (received > 0) { command = Encoding.UTF8.GetString(buffer).TrimEnd('\0'); Console.WriteLine(command); if (!TryToParse(command)) { commandToProcess = command; if (CheckIfDate(command)) { await ProcessCommand(CheckForSongUpdate); } else { await ProcessCommand(AddToQueue); } } else { if (m_parseResult == EXIT_CMD) { //connection lost // received = 0; // m_peerStream.Dispose(); // m_peerStream.Close(); remoteDevice.Close(); break; } else { await ProcessCommand(m_parseResult); } } } } catch (Exception ex) { Logger.LogFile(ex.Message, "", "AcceptConnection", ex.LineNumber(), "BlueToothConnect"); } } } }