public void StopStartStop()
        {
            TestLsnrRfcommPort port0 = Init_OneListenerStartedTwice();
            BluetoothListener  lsnr  = new BluetoothListener(BluetoothService.VideoSource);

            lsnr.Start();
            lsnr.Stop();
            lsnr.Start();
            //
            lsnr = null;
            GC.Collect();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Esempio n. 2
0
        private void ServerConnectThread()
        {
            BluetoothListener blueListner = new BluetoothListener(mUUID);
            blueListner.Start();
            startScan();

        }
        } //

        /*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. 4
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");
                }
            }
        }
Esempio n. 5
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");
                }
            }
        }
Esempio n. 6
0
        public void StartService()
        {
            BluetoothListener listener = new BluetoothListener(BluetoothService.SerialPort);

            //listener.Server.
            listener.Start();
            Console.WriteLine("Service started!");
            //listener.
            BluetoothClient client = listener.AcceptBluetoothClient();

            Console.WriteLine("Got a request!");

            Stream peerStream = client.GetStream();

            string dataToSend = "Hello from service!";

            // Convert dataToSend into a byte array
            byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(dataToSend);

            // Output data to stream
            peerStream.Write(dataBuffer, 0, dataBuffer.Length);

            byte[] buffer = new byte[2000];
            while (true)
            {
                if (peerStream.CanRead)
                {
                    peerStream.Read(buffer, 0, 50);
                    string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 50);
                    peerStream.Write(dataBuffer, 0, dataBuffer.Length);
                    peerStream.Flush();
                    Console.WriteLine("Receiving data: " + data);
                }
            }
        }
Esempio n. 7
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. 8
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. 9
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. 10
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. 11
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) { }
                }
            }
        }
Esempio n. 12
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. 13
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");
                }
            }
        }
Esempio n. 14
0
 public void ServerConnectThread()
 {
     serverstarted = true;
     try
     {
         updat("serveur activé");
         BluetoothListener bluelistener = new BluetoothListener(MyID);
         bluelistener.Start();
         BluetoothClient conn = bluelistener.AcceptBluetoothClient();
         updat("client est connecter!");
         Stream mstream = conn.GetStream();
         while (true)
         {
             byte[] recieved = new byte[1024];
             mstream.Read(recieved, 0, recieved.Length);
             updat("Message reçue:" + Encoding.ASCII.GetString(recieved));
             byte[] sent = Encoding.ASCII.GetBytes(bltexte.Text);
             mstream.Write(sent, 0, sent.Length);
         }
     }
     catch (PlatformNotSupportedException)
     {
         updat("client est deconnecté!");
     }
 }
Esempio n. 15
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. 16
0
        public void StartSynchronousServer()
        {
            Log.write("Initializing server w/ UUID: " + UUID.ToString());

            var bluetoothListener = new BluetoothListener(UUID);

            bluetoothListener.Start();

            Log.write("Server socket initialized.");

            while (m_ServerRunning)
            {
                Log.write("Waiting for connection...");
                BluetoothClient connection = bluetoothListener.AcceptBluetoothClient();

                Log.write("Connection established.");
                BTDataIO clientStream = new BTDataIO(connection.GetStream());

                while (clientStream.CanRead())
                {
                    ReadAndExecuteNextActions(clientStream);
                }
            }

            Log.write("Server closed.");
        }
        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);
                }
            }
        }
Esempio n. 18
0
        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");
        }
        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. 21
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. 22
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();
            //...
        }
Esempio n. 23
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. 24
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;
        }
        public BluetoothClientListener()
        {
            _bluetoothGuid = Guid.NewGuid();

            _listener = new BluetoothListener(_bluetoothGuid);
            _listener.Start();
        }
Esempio n. 26
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);
                }
            }
        }
        public override void receive_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();
                scan_transfer_speed();

                _bluetooth_guid     = Guid.Parse(bluid);
                _bluetooth_listener = new BluetoothListener(_bluetooth_guid);
                _bluetooth_listener.Start();

                _bluetooth_client = _bluetooth_listener.AcceptBluetoothClient();
                _netstream        = _bluetooth_client.GetStream();

                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                int length;
                _buffer = new byte[65000];

                while ((length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    while (_writing)
                    {
                    }

                    _count_received_bytes += length;

                    _filestream.Write(_buffer, 0, length);
                }

                _timer_ts.Close();
                _stopwatch.Stop();

                int _transferspeed = _count_received_bytes / 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), "kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message);

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _bluetooth_listener.Stop();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }
Esempio n. 28
0
        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);
        }
Esempio n. 29
0
        private void StartListener()
        {
            var lsnr = new BluetoothListener(OurServiceClassId);

            lsnr.ServiceName = OurServiceName;
            lsnr.Start();
            _lsnr = lsnr;
            ThreadPool.QueueUserWorkItem(ListenerAccept_Runner, lsnr);
        }
Esempio n. 30
0
        private void btnListen_Click(object sender, EventArgs e)
        {
            btnListen.Enabled = false;

            bl.Start();
            running = true;

            bgworkerRunning.RunWorkerAsync();
        }