Esempio n. 1
0
        public void ReceiverConnectThread()
        {
            connectionRunning = true;
            UpdateUI("Started ... Waiting for Connection ...");
            BluetoothListener bluetoothListener = new BluetoothListener(BluetoothService.SerialPort);

            bluetoothListener.Start();
            BluetoothClient bluetoothConnection = bluetoothListener.AcceptBluetoothClient();

            UpdateUI("Device Connected");
            Stream mStream = bluetoothConnection.GetStream();

            while (true)
            {
                try
                {
                    //handle receiver connection
                    byte[] receivedData = new byte[1024];
                    mStream.Read(receivedData, 0, receivedData.Length);
                    UpdateUI("Data Received: " + Encoding.ASCII.GetString(receivedData));
                    byte[] sentData = Encoding.ASCII.GetBytes("Hello World");
                    mStream.Write(sentData, 0, sentData.Length);
                }
                catch (IOException exception)
                {
                    UpdateUI("Bluetooth Disconnected");
                }
            }
        }
        public void StopNoStart()
        {
            TestLsnrRfcommPort port0 = Init_OneListener();
            BluetoothListener  lsnr  = new BluetoothListener(BluetoothService.VideoSource);

            lsnr.Stop();
        }
Esempio n. 3
0
        /// <summary>
        /// Starts a Bluetooth server and listens for incoming <see cref="BluetoothConnection"/>s.
        /// </summary>
        public async Task StartBluetoothListener()
        {
            if (IsBluetoothOnline || !AllowBluetoothConnections || !BluetoothConnection.IsBluetoothSupported)
            {
                return;
            }

            bluetoothListener = new BluetoothListener(ConnectionFactory.GUID);
            bluetoothListener.Start();
            IsBluetoothOnline = !IsBluetoothOnline;

            while (IsBluetoothOnline)
            {
                BluetoothClient bluetoothClient = await Task.Factory.FromAsync(bluetoothListener.BeginAcceptBluetoothClient, bluetoothListener.EndAcceptBluetoothClient, TaskCreationOptions.PreferFairness);

                BluetoothConnection bluetoothConnection = ConnectionFactory.CreateBluetoothConnection(bluetoothClient);
                bluetoothConnection.NetworkConnectionClosed += connectionClosed;

                //Inform all subscribers.
                if (connectionEstablished != null &&
                    connectionEstablished.GetInvocationList().Length > 0)
                {
                    connectionEstablished(bluetoothConnection, ConnectionType.Bluetooth);
                }
            }
        }
Esempio n. 4
0
        void Server1()
        {
            //...
            Guid serviceClass;

            serviceClass = BluetoothService.SerialPort;
            // - or - etc
            // serviceClass = MyConsts.MyServiceUuid
            //
            var lsnr = new BluetoothListener(serviceClass);

            lsnr.Start();


            // Now accept new connections, perhaps using the thread pool to handle each
            BluetoothClient conn       = lsnr.AcceptBluetoothClient();
            Stream          peerStream = conn.GetStream();

            ///...

            // etc
            conn       = lsnr.AcceptBluetoothClient();
            peerStream = conn.GetStream();
            //...
        }
        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("TAG: ServerConnectThread Message: server started,waiting for clients");
            BluetoothListener blueListener = new BluetoothListener(mUUID);

            blueListener.Start();


            updateUI("TAG: ServerConnectThread Message:Client has connected");


            while (true)
            {
                BluetoothClient conn    = blueListener.AcceptBluetoothClient();
                Stream          mStream = conn.GetStream();
                try
                {
                    //handle server connection
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    updateUI(Encoding.UTF8.GetString(received));
                }
                catch (IOException e)
                {
                    updateUI("TAG: ServerConnectedThread Message : Program catch a some error: " + e.Message);
                }
            }
        }
        public BluetoothClientListener()
        {
            _bluetoothGuid = Guid.NewGuid();

            _listener = new BluetoothListener(_bluetoothGuid);
            _listener.Start();
        }
Esempio n. 7
0
        public static void connectServerExample()
        {
            // TODO synchronous server
            Console.WriteLine("Begin init.");
            var bluetoothListener = new BluetoothListener(UUID);

            bluetoothListener.Start();

            Console.WriteLine("Begin accepting socket.");
            BluetoothClient connection       = bluetoothListener.AcceptBluetoothClient();
            Stream          connectionStream = connection.GetStream();

            Console.WriteLine("Begin reading.");

            while (connectionStream.CanRead)
            {
                int data = connectionStream.ReadByte();

                if (data != -1)
                {
                    Console.WriteLine(data);
                }
            }

            Console.WriteLine("End reading.");
        }
Esempio n. 8
0
        public Bluetooth(Guid applicationGuid, MainWindow mwObject)
        {
            clientSocket = new BluetoothListener(applicationGuid);
            clientWorker = new BackgroundWorker();

            this.mwObject = mwObject;
        }
        private void BluetoothAccept(IAsyncResult result)
        {
            lock (bluetoothLocker)
                if (this.bluetoothListener == null)
                {
                    return;
                }

            BluetoothListener listener = (BluetoothListener)result.AsyncState;
            BluetoothClient   connectedClient;

            lock (bluetoothLocker)
                connectedClient = listener.EndAcceptBluetoothClient(result);
            this.acceptResult = ((BluetoothListener)result.AsyncState).BeginAcceptBluetoothClient(BluetoothAccept, result.AsyncState);
            //BluetoothClient connectedClient = (BluetoothClient)result;
            int tempClientIndex;

            lock (clientListLocker)
            {
                tempClientIndex = clientIndex++;
                clientList.Add(tempClientIndex, connectedClient);
            }
            CreateClient(connectedClient, tempClientIndex);
            mainForm.ConnectDrone(tempClientIndex);
            mainForm.UpdateLog("Client" + tempClientIndex.ToString() + " Accepted");
        }
Esempio n. 10
0
 public BluetoothManager(BluetoothServer owner)
 {
     server            = owner;
     clientScanner     = new ClientScanner(this);
     bluetoothListener = NewBluetoothListener();
     BluetoothServerStart();
 }
Esempio n. 11
0
        public Device(string address, List <Tuple <string, string, int> > services)
        {
            this.clients = new Dictionary <string, KeyValuePair <BluetoothClient, int> >();
            data         = new ConcurrentQueue <KeyValuePair <string, byte[]> >();
            foreach (var service in services)
            {
                BluetoothListener l = new BluetoothListener(new Guid(service.Item2));
                l.Start();
                this.clients.Add(
                    service.Item1,
                    new KeyValuePair <BluetoothClient, int>(
                        l.AcceptBluetoothClient(),
                        service.Item3
                        )
                    );
            }

            /*
             * this.clients = services.Select(s =>
             *  new KeyValuePair<string, KeyValuePair<BluetoothClient, int>>(
             *      s.Item1,
             *      new KeyValuePair<BluetoothClient, int>(
             *          new BluetoothClient(
             *              new BluetoothEndPoint(
             *                  BluetoothAddress.Parse(address),
             *                  new Guid(s.Item2)
             *              )
             *          ), s.Item3
             *      )
             * )).ToDictionary(kv => kv.Key, kv => kv.Value);*/

            this.threads = clients.Select(c =>
                                          new Thread(() => Listen(c.Key, c.Value.Key, c.Value.Value))
                                          ).ToArray();
        }
Esempio n. 12
0
 //[Test]
 public void BtLsnrAccept2_None()
 {
     // No usage exceptions
     var lsnr  = new BluetoothListener(Guid.Empty);
     var task  = lsnr.AcceptBluetoothClientAsync(null);
     var task2 = lsnr.AcceptSocketAsync(null);
 }
        } //

        /*public BtChatListener(string serviceClassId, string xThreadName)
         * {
         *  //"34b1cf4d-1069-4ad6-89b6-e161d79be4d8");
         *  _serviceClassId = new Guid(serviceClassId);
         *  ThreadName = xThreadName;
         * } //*/

        public bool Start()
        {
            if (!_ExitLoop)
            {
                Console.WriteLine("Listener running already");
                return(false);
            }
            _ExitLoop = false;

            try {
                _Listener = new BluetoothListener(_serviceClassId)
                {
                    ServiceName = "MyService"
                };
                _Listener.Start();

                Thread lThread = new Thread(new ThreadStart(LoopWaitingForClientsToConnect));
                lThread.IsBackground = true;
                lThread.Name         = ThreadName + "WaitingForClients";
                lThread.Start();

                return(true);
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
            return(false);
        } //
Esempio n. 14
0
        private void ServerConnectThread()
        {
            BluetoothListener blueListner = new BluetoothListener(mUUID);
            blueListner.Start();
            startScan();

        }
Esempio n. 15
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            setButtonEnabled = new setButtonEnabledHandler(setButtonEnabledMethod);
            setRcvText       = new setTextHandler(setRcvTextMethod);
            setLabelStatus   = new setLabelStatusHandler(setLabelStatusMethod);
            BluetoothRadio br = BluetoothRadio.PrimaryRadio;

            if (br == null)
            {
                MessageBox.Show("No supported Bluetooth radio/stack found.");
                btnListen.Enabled = false;
            }
            else if (br.Mode != InTheHand.Net.Bluetooth.RadioMode.Discoverable)
            {
                DialogResult rslt = MessageBox.Show("Make BluetoothRadio Discoverable?", "Bluetooth Remote Listener", MessageBoxButtons.YesNo);
                if (rslt == DialogResult.Yes)
                {
                    br.Mode = RadioMode.Discoverable;
                }
                else
                {
                    btnListen.Enabled = false;
                }
            }
            bl = new BluetoothListener(service);
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the ObexListener class specifiying the transport to use.
        /// </summary>
        /// -
        /// <param name="transport">Specifies the transport protocol to use.
        /// </param>
        public ObexListener(ObexTransport transport)
        {
            switch (transport)
            {
            case ObexTransport.Bluetooth:
                ServiceRecord record = CreateServiceRecord();
                bListener = new BluetoothListener(BluetoothService.ObexObjectPush, record);
                bListener.ServiceClass = ServiceClass.ObjectTransfer;
                break;

            case ObexTransport.IrDA:
#if NO_IRDA
                throw new NotSupportedException("No IrDA on this platform.");
#else
                iListener = new IrDAListener("OBEX");
                break;
#endif
            case ObexTransport.Tcp:
                tListener = new TcpListener(IPAddress.Any, 650);
                break;

            default:
                throw new ArgumentException("Invalid transport specified");
            }
            this.transport = transport;
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("--- Copter Emulator ---");
            System.Console.WriteLine("Listening for commands...");
            System.Console.WriteLine();

            //Guid serviceClass = BluetoothService.SerialPort;
            var lsnr = new BluetoothListener(CopterGUID);

            lsnr.Start();

            BluetoothClient conn       = lsnr.AcceptBluetoothClient();
            Stream          peerStream = conn.GetStream();

            byte[] buffer = new byte[256];

            while (!false)
            {
                int readSize = peerStream.Read(buffer, 0, buffer.Length);
                if (readSize > 0)
                {
                    String s = System.Text.Encoding.ASCII.GetString(buffer, 0, readSize);
                    System.Console.Write(s);
                }
            }
        }
Esempio n. 18
0
        private void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("server started");
            BluetoothListener btListener = new BluetoothListener(myGuid);

            btListener.Start();
            BluetoothClient client = btListener.AcceptBluetoothClient();

            updateUI("Client has connected");
            aStream = client.GetStream();

            while (client.Connected)
            {
                isWorking = true;
                try
                {
                    string tmp = GetData();
                    okno.waitForData(tmp);
                }
                catch (IOException exc)
                {
                    updateUI("Client disconnected.\n" + exc.ToString());
                }
            }

            isWorking = false;
        }
Esempio n. 19
0
        public void ServerConnectThread()
        {
            updateUI("Server started, waiting for client");
            bluetoothListener = new BluetoothListener(mUUID);
            bluetoothListener.Start();
            conn = bluetoothListener.AcceptBluetoothClient();

            updateUI("Client has connected");
            connected = true;

            //Stream mStream = conn.GetStream();
            mStream = conn.GetStream();

            while (connected)
            {
                try
                {
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    string receivedString = Encoding.ASCII.GetString(received);
                    //updateUI("Received: " + receivedString);
                    handleBluetoothInput(receivedString);
                    //byte[] send = Encoding.ASCII.GetBytes("Hello world");
                    //mStream.Write(send, 0, send.Length);
                }
                catch (IOException e)
                {
                    connected = false;
                    updateUI("Client disconnected");
                    disconnectBluetooth();
                }
            }
        }
Esempio n. 20
0
        public void ServerConnectThread()
        {
            serverStarted = true;
            UpdateUI("Server started ... Waiting for client");
            BluetoothListener bluetoothListener = new BluetoothListener(mUUID);

            bluetoothListener.Start();
            BluetoothClient bluetoothClient = bluetoothListener.AcceptBluetoothClient();

            UpdateUI("Server is connected ...");
            Stream mStream = bluetoothClient.GetStream();

            while (true)
            {
                try
                {
                    //handle server connection
                    byte[] recieved = new byte[1024];
                    mStream.Read(recieved, 0, recieved.Length);
                    UpdateUI("Recieved: " + Encoding.ASCII.GetString(recieved) + Environment.NewLine);
                    byte[] sent = Encoding.ASCII.GetBytes("Data Sent: " + recieved);
                    mStream.Write(sent, 0, sent.Length);
                }
                catch (IOException exception)
                {
                    UpdateUI("Client has disconnected");
                }
            }
        }
        public void StartListening(Guid serviceClassId)
        {
            if (_isConnected)
            {
                throw new BluetoothServiceException("Service cannot start listing when it is a sender.");
            }

            if (_isListening)
            {
                throw new BluetoothServiceException("Service is already listening.");
            }

            _isListening = true;
            if (_cancelToken != null && _listener != null)
            {
                Dispose(true);
            }
            _listener = new BluetoothListener(serviceClassId)
            {
                ServiceName = "MyService"
            };

            _listener.Start();
            _cancelToken = new CancellationTokenSource();

            Task.Run(() => Listener(_cancelToken));
        }
Esempio n. 22
0
        public void ServerConnectThread()
        {
            updateUI("Server iniciado...");
            serverStarted = true;

            while (true)
            {
                updateUI("Aguardando por clientes...");
                BluetoothListener blueListener = new BluetoothListener(mUUID);
                blueListener.Start();
                BluetoothClient conn = blueListener.AcceptBluetoothClient();
                updateUI("Cliente conectado");

                Stream mStream   = conn.GetStream();
                var    connected = true;
                while (connected)
                {
                    try
                    {
                        //handle server connection
                        byte[] received = new byte[1024];
                        mStream.Read(received, 0, received.Length);
                        updateUI("Recebido: " + Encoding.ASCII.GetString(received) + Environment.NewLine);
                        byte[] sent = Encoding.ASCII.GetBytes("Mensagem recebida!");
                        mStream.Write(sent, 0, sent.Length);
                    }
                    catch (IOException)
                    {
                        updateUI("Cliente foi desconectado!");
                        connected = false;
                    }
                }
            }
        }
Esempio n. 23
0
        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("Server started, waiting for clients");
            blueListener = new BluetoothListener(mUUID);
            blueListener.Start();
            BluetoothClient conn = blueListener.AcceptBluetoothClient();

            updateUI("Client has connected");

            Stream mStream = conn.GetStream();

            while (true)
            {
                try
                {
                    //handle server connection
                    byte[] received = new byte[1024];
                    string received_msg;
                    mStream.Read(received, 0, received.Length);
                    received_msg = Encoding.ASCII.GetString(received);

                    //Bluetooth protocol parsing
                    parse_received(received_msg);
                }
                catch (IOException)
                {
                    updateUI("Client has disconnected!!!");
                }
            }
        }
Esempio n. 24
0
        public void AcceptAndListen()
        {
            while (true)
            {
                if (isConnected)
                {
                    try {
                        ReceiveMessages();
                    }catch (Exception e) {
                        isConnected = btClient.Connected;
                        Console.WriteLine(e.Message);
                    }
                }
                else
                {
                    //TODO: if there is no connection
                    // accepting
                    try{
                        btListener = new BluetoothListener(BluetoothService.RFCommProtocol);

                        Console.WriteLine(BluetoothService.RFCommProtocol);
                        btListener.Start();
                        btClient    = btListener.AcceptBluetoothClient();
                        isConnected = btClient.Connected;
                        Console.WriteLine("연결완료");
                    }catch (Exception) { }
                }
            }
        }
        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");
        }
Esempio n. 26
0
        void Receive()
        {
            var token = cts.Token;

            try
            {
                var _listener = new BluetoothListener(ServiceId)
                {
                    ServiceName = "MyService"
                };
                _listener.Start();
                using (token.Register(_listener.Stop))
                {
                    while (true)
                    {
                        using (var client = _listener.AcceptBluetoothClient())
                        {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            ProcessClient(client);
                        }
                    }
                }
            }
            catch (SocketException)
            {
                // stoped receiving
            }
        }
Esempio n. 27
0
        public void Listen(Guid service)
        {
            BluetoothListener listener = new BluetoothListener(BluetoothAddress.None, service);

            listener.Start(10);
            listener.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), listener);
        }
Esempio n. 28
0
 private void ReceiveData()
 {
     try
     {
         Guid mGUID = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
         m_bluetoothListener = new BluetoothListener(mGUID);
         m_bluetoothListener.Start();
         m_Blueclient  = m_bluetoothListener.AcceptBluetoothClient();
         m_isConnected = true;
     }
     catch (Exception)
     {
         m_isConnected = false;
     }
     while (m_isConnected)
     {
         string receive = string.Empty;
         if (m_Blueclient == null)
         {
             continue;
         }
         try
         {
             peerStream = m_Blueclient.GetStream();
             byte[] buffer = new byte[6];
             peerStream.Read(buffer, 0, 6);
             receive = Encoding.UTF8.GetString(buffer).ToString();
         }
         catch (System.Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         Thread.Sleep(100);
     }
 }
Esempio n. 29
0
        public void StartStopStart()
        {
            BluetoothListener lsnr = new BluetoothListener(DummySvcClass);

            DoTestStartStop(lsnr);
            DoTestStartStop(lsnr);
        }
Esempio n. 30
0
        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("Server Started. Wating for Client");
            BluetoothListener blueListener = new BluetoothListener(mWid);

            blueListener.Start();
            BluetoothClient conn = blueListener.AcceptBluetoothClient();

            updateUI("Client Connected");
            Stream mStream = conn.GetStream();

            while (true)
            {
                try
                {
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    updateUI("Received:" + Encoding.ASCII.GetString(received));
                    byte[] sent = Encoding.ASCII.GetBytes("Hello World");
                    mStream.Write(sent, 0, sent.Length);
                }
                catch (IOException exception)
                {
                    updateUI("Client has Disconnected");
                }
            }
        }