Ejemplo n.º 1
0
        public Boolean sendMessage(String msg)
        {
            try
            {
                if (!msg.Equals(""))
                {
                    UTF8Encoding  encoder = new UTF8Encoding();
                    NetworkStream stream  = btClient.GetStream();
                    stream.Write(encoder.GetBytes(msg + "\n"),
                                 0, encoder.GetBytes(msg).Length);
                    stream.Flush();
                }
            }
            catch (Exception ex)
            {
                UpdateLogTextFromThread("There is an error while sending message");
                UpdateLogTextFromThread(ex.Message);

                try
                {
                    isConnected = btClient.Connected;
                    btClient.GetStream().Close();
                    btClient.Dispose();
                    btListener.Server.Dispose();
                    btListener.Stop();
                }
                catch (Exception)
                {
                }
                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Stops the listening from Senders.
 /// </summary>
 public void Stop()
 {
     if (WasStarted)
     {
         WasStarted = false;
         _listener.Stop();
         _cancelListnerSource.Cancel();
     }
 }
Ejemplo n.º 3
0
        //function to send message to the client
        public Boolean sendMessage(String msg)
        {
            try
            {
                if (!msg.Equals(""))
                {
                    UTF8Encoding encoder = new UTF8Encoding();
                    if (isConnected)
                    {
                        NetworkStream stream = btClient.GetStream();
                        stream.Write(encoder.GetBytes(msg + "\n"), 0, encoder.GetBytes(msg).Length);
                        stream.Flush();
                    }
                    if (isConnectedIP)
                    {
                        int    bufferCount = 0;
                        byte[] buffer      = new byte[4096];
                        buffer      = ASCIIEncoding.UTF8.GetBytes(msg);
                        bufferCount = ASCIIEncoding.UTF8.GetByteCount(msg);
                        acceptedSocket.Send(buffer, 0, bufferCount, SocketFlags.None);
                    }
                    if (isConnectedServer)
                    {
                        NetworkStream stream = mClient.GetStream();
                        stream.Write(encoder.GetBytes(msg + "\n"), 0, encoder.GetBytes(msg).Length);
                        stream.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                UpdateLogTextFromThread("There is an error while sending message");
                UpdateLogTextFromThread(ex.Message);
                try
                {
                    isConnected = btClient.Connected;
                    btClient.GetStream().Close();
                    btClient.Dispose();
                    btListener.Server.Dispose();
                    btListener.Stop();
                }
                catch (Exception)
                {
                }

                return(false);
            }

            return(true);
        }
        public void OneConnection_PendingBeforeSyncAccept()
        {
            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);

            try {
                Assert.IsFalse(lsnr.Pending(), "!Pending before Start");
                lsnr.Start();
                port0.AssertOpenServerCalledAndClear(29);            //adter Start?
                TestLsnrRfcommPort port1 = new TestLsnrRfcommPort();
                port1.SetOpenServerResult(PORT_RETURN_CODE.SUCCESS); // now begun immediately
                f.queueIRfCommPort.Enqueue(port1);
                Assert.IsFalse(lsnr.Pending(), "!Pending before");
                port0.NewEvent(PORT_EV.CONNECTED);
                Thread.Sleep(100);
                Assert.IsTrue(lsnr.Pending(), "Pending");
                BluetoothClient cli    = lsnr.AcceptBluetoothClient();
                TestSdpService2 sdpSvc = f.GetTestSdpService();
                Assert.AreEqual(0, sdpSvc.NumDisposeCalls, "NumDisposeCalls");
                lsnr.Stop();
                Assert.AreEqual(1, sdpSvc.NumDisposeCalls, "NumDisposeCalls");
                //
                Assert.IsTrue(cli.Connected, "cli.Connected");
                //TODOAssert.AreEqual(0, f.queueIRfCommPort.Count, "Used both ports");
                //TODO 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
                    );
                //
                //
            } finally {
                lsnr.Stop(); // See errors that might otherwise occur on the Finalizer.
            }
        }
        } //

        private void LoopWaitingForClientsToConnect()
        {
            try {
                while (!_ExitLoop)
                {
                    Console.WriteLine("waiting for a client");
                    BluetoothClient lClient          = _Listener.AcceptBluetoothClient();
                    string          lClientIpAddress = lClient.Client.LocalEndPoint.ToString();
                    Console.WriteLine("new client connecting: " + lClientIpAddress);
                    if (_ExitLoop)
                    {
                        break;
                    }
                    lock (_Clients) _Clients.Add(lClient);

                    Thread lThread = new Thread(new ParameterizedThreadStart(LoopRead));
                    lThread.IsBackground = true;
                    lThread.Name         = ThreadName + "CommunicatingWithClient";
                    lThread.Start(lClient);
                    OnClientConnected(new BtChatConnectedEventArgs(lClientIpAddress));
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
            finally {
                _ExitLoop = true;
                if (_Listener != null)
                {
                    _Listener.Stop();
                }
            }
        } //
Ejemplo n.º 6
0
        private void discon()           ///disposes all resources used
        {
            //unsubscribeHook();
            if (btListener != null)
            {
                btListener.Stop();
                btListener = null;
            }

            if (reader != null)
            {
                reader.Close();
                reader = null;
            }

            if (btClient != null)
            {
                btClient.Dispose();
                btClient = null;
            }

            this.Dispatcher.Invoke((Action)(() =>
            {
                start.IsEnabled = true;
                disconnect.IsEnabled = false;
            }));
        }
        public void StopNoStart()
        {
            TestLsnrRfcommPort port0 = Init_OneListener();
            BluetoothListener  lsnr  = new BluetoothListener(BluetoothService.VideoSource);

            lsnr.Stop();
        }
        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");
        }
Ejemplo n.º 9
0
 private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     // stop receive loop
     listening = false;
     btListener.Stop();
     Application.Exit();
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Stops the Bluetooth listener, so that no new <see cref="BluetoothConnection"/>s can connect.
 /// </summary>
 public void StopBluetoothListener()
 {
     if (IsBluetoothOnline)
     {
         bluetoothListener.Stop();
     }
     IsBluetoothOnline = !IsBluetoothOnline;
 }
        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);
            }
        }
Ejemplo n.º 12
0
 public void stop()
 {
     isStopped = true;
     bluetoothListener.Stop();
     if (activeStream != null)
     {
         activeStream.Close();
     }
 }
Ejemplo n.º 13
0
        /// <inheritdoc />
        internal override void StopListening()
        {
            IsListening = false;

            try
            {
                listenerInstance.Stop();
            }
            catch (Exception) { }
        }
Ejemplo n.º 14
0
 internal void Dispose()
 {
     try
     {
         isRunning = false;
         serverSocket.Stop();
     }
     catch (Exception exception)
     { }
 }
        public void TestCreateAVariousRecord()
        {
            ServiceRecord record = CreateAVariousRecord();

#if false
            TestWcLsnrBluetoothFactory f = new TestWcLsnrBluetoothFactory();
            BluetoothFactory.SetFactory(f);
            //----
            int port = 19;
            ServiceRecordHelper.SetRfcommChannelNumber(record, port);
            //
            ISdpService     x0 = SdpService.CreateCustom(record);
            TestSdpService2 x  = (TestSdpService2)x0;
#endif
            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,
                                                           record);
            lsnr.Start();
            int port = lsnr.LocalEndPoint.Port;
            lsnr.Stop();
            //
            TestSdpService2 x = f.GetTestSdpService();
            x.AssertCalls(
                // Well-known
                "AddServiceClassIdList: <00001400-0000-1000-8000-00805f9b34fb>" + NewLine
                + "AddRFCommProtocolDescriptor: " + port + NewLine
                // Eeeeeeech, how to detect all possible LangOffset_WellKnown strings!!!!
                + "AddAttribute: id: 0x0006, dt: DATA_ELE_SEQ, len: 9, val: "
                + "09-65-6E-" + "09-00-6A-" + "09-01-00" + NewLine
                + "AddAttribute: id: 0x0100, dt: TEXT_STR, len: 4, val: 61-6C-61-6E" + NewLine
                + "AddAttribute: id: 0x0401, dt: DATA_ELE_ALT, len: 66, val: "
                + "35-2F-35-2D-25-0C-61-62-63-64-C3-A9-66-67-68-C4-"
                + "AD-6A-45-1A-68-74-74-70-3A-2F-2F-65-78-61-6D-70-"
                + "6C-65-2E-63-6F-6D-2F-66-6F-6F-2E-74-78-74-09-FE-"
                + "12-25-0C-61-62-63-64-C3-A9-66-67-68-C4-AD-6A-09-"
                + "12-34" + NewLine
                + "AddAttribute: id: 0x4015, dt: UINT, len: 1, val: 15" + NewLine
                + "AddAttribute: id: 0x4016, dt: UINT, len: 2, val: 00-16" + NewLine
                + "AddAttribute: id: 0x4017, dt: UINT, len: 4, val: 00-00-00-17" + NewLine
                + "AddAttribute: id: 0x401E, dt: TWO_COMP_INT, len: 1, val: 1E" + NewLine
                + "AddAttribute: id: 0x401F, dt: TWO_COMP_INT, len: 2, val: 00-1F" + NewLine
                + "AddAttribute: id: 0x4020, dt: TWO_COMP_INT, len: 4, val: 00-00-00-20" + NewLine
                + "AddAttribute: id: 0x4028, dt: UUID, len: 2, val: 00-28" + NewLine
                + "AddAttribute: id: 0x4029, dt: UUID, len: 4, val: 00-00-00-29" + NewLine
                + "AddAttribute: id: 0x402A, dt: UUID, len: 16, val: 00-00-00-2A-00-00-10-00-80-00-00-80-5F-9B-34-FB" + NewLine
                + "AddAttribute: id: 0x402C, dt: BOOLEAN, len: 1, val: 01" + NewLine
                );
        }
Ejemplo n.º 16
0
 public void DisconnectClient()
 {
     try
     {
         Client.BTClient.Close();
         BTListener.Stop();
         BTListener = null;
     }
     catch
     {
     }
 }
Ejemplo n.º 17
0
        private void end_Click_1(object sender, EventArgs e)
        {
            if (_serverStarted)
            {
                _serverThread?.Abort();
                _client?.Close();
                _blueListener.Stop();
                _serverStarted = false;

                UpdateUi("Server Stopped");
            }
        }
        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
                );
        }
 /// <summary>
 /// The dispose.
 /// </summary>
 /// <param name="disposing">
 /// The disposing.
 /// </param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_cancelSource != null)
         {
             _listener.Stop();
             _listener = null;
             _cancelSource.Dispose();
             _cancelSource = null;
         }
     }
 }
Ejemplo n.º 20
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_cancelSource != null)
         {
             _listener.Stop();
             _listener = null;
             _cancelSource.Dispose();
             _cancelSource = null;
         }
     }
 }
Ejemplo n.º 21
0
        private void disconnectBluetooth()
        {
            connected = false;
            updateUI("Client disconnected");

            conn.Close();
            conn = null;

            bluetoothListener.Stop();
            bluetoothListener = null;

            bluetoothServerThread.Abort();
        }
Ejemplo n.º 22
0
 public void ServerClose()
 {
     LogHelper.Info(string.Format("Client disconnected, Stopping Server"));
     try
     {
         _bluetoothListener.Stop();
         _bluetoothClient.Dispose();
     }
     catch (Exception e)
     {
         LogHelper.Error(e.ToString());
     }
 }
        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();
        }
Ejemplo n.º 24
0
        public void GoodOne()
        {
            Guid          uuid = BluetoothService.GenericAudio;
            ServiceRecord rcd  = new ServiceRecord(
                new ServiceAttribute(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList,
                                     new ServiceElement(ElementType.ElementSequence,
                                                        new ServiceElement(ElementType.Uuid128, uuid))),
                new ServiceAttribute(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList,
                                     ServiceRecordHelper.CreateRfcommProtocolDescriptorList())
                );
            BluetoothListener lsnr = new BluetoothListener(uuid, rcd);

            lsnr.Start();
            lsnr.Stop();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Threaded loop discovers new devices in range and sends this Members profile
        /// if they have not yet received it.
        /// </summary>
        public void DiscoverLoop()
        {
            // on exit, run is set to false to terminate all threads
            while (run)
            {
                // create a new bluetooth client object
                BluetoothClient bt = new BluetoothClient();

                // return a maximum of 10 devices
                bTDevices = bt.DiscoverDevices(10);

                //close the bluetooth client object
                bt.Close();

                // loop through all the devices found
                for (int i = 0; i < BTDevices.Length; i++)
                {
                    // check again if the application is exiting and terminate threads
                    // this makes the application end much faster
                    if (!run)
                    {
                        // stop the listener
                        btListener.Stop();
                        // exit the loop
                        break;
                    }

                    try
                    {
                        // the device isnt looing at itself
                        if (BTDevices[i].DeviceAddress.ToString() != this.MACAddress)
                        {
                            // if the device name is not in the match list
                            if (!MainForm.member.MatchExists(BTDevices[i].DeviceAddress.ToString()))
                            {   //Send profile and request that a profile not be returned by using "0" parameter
                                SendBluetoothProfile(bTDevices[i].DeviceAddress, 0);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //throw e;
                        // an exception will be thrown if the remote device doesnt reply in time
                        // this is quite a frequent occurance due to the nature of mobile bluetooth
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public void GoodOneDifferentUuids_EndPoint()
        {
            Guid          uuid1 = BluetoothService.GenericAudio;
            Guid          uuid2 = BluetoothService.HardcopyCableReplacement;
            ServiceRecord rcd   = new ServiceRecord(
                new ServiceAttribute(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList,
                                     new ServiceElement(ElementType.ElementSequence,
                                                        new ServiceElement(ElementType.Uuid128, uuid1))),
                new ServiceAttribute(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList,
                                     ServiceRecordHelper.CreateRfcommProtocolDescriptorList())
                );
            BluetoothListener lsnr = new BluetoothListener(new BluetoothEndPoint(BluetoothAddress.None, uuid2), rcd);

            lsnr.Start();
            lsnr.Stop();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// The dispose.
        /// </summary>
        /// <param name="disposing">
        /// The disposing.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (_cancelSource == null)
            {
                return;
            }

            _listener.Stop();
            _listener = null;
            _cancelSource.Dispose();
            _cancelSource = null;
        }
        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");
        }
Ejemplo n.º 29
0
        // 监听线程函数,用来监听来自手机端的请求并且分配各个用户的权限。
        private void ListenLoop()
        {
            while (listening)
            {
                try
                {
                    System.IO.Stream tempStream;
                    client = listener.AcceptBluetoothClient();
                    clientList.Add(client);
                    // 获取客户端信息(学生或者老师)
                    tempStream = client.GetStream();
                    byte[] mark;
                    int    length;
                    mark   = new byte[20];
                    length = tempStream.Read(mark, 0, mark.Length);
                    string right = System.Text.Encoding.ASCII.GetString(mark, 0, length);
                    if (right == "teacher")
                    {
                        stream = tempStream;
                        sendfileList.Add("tom.jpg");
                        WriteMessage("tom");
                        sendfileList.Add("jake.jpg");
                        WriteMessage("jake");
                        sendfileList.Add("sherry.jpg");
                        WriteMessage("sherry");
                    }
                    if (right.StartsWith("student"))
                    {
                        // 提取right中的学生名称并加进去listBox里面
                        string studentName = right.Substring(7, right.Length - 7);
                        WriteMessage(studentName);
                    }
                    SIGN_STREAMSETUP = true;

                    // 远程设备连接后,启动recieve程序
                    receiving = true;
                    new System.Threading.Thread(ReceiveLoop).Start((Object)client);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    continue;
                }
            }
            listener.Stop();
        }
        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
                );
        }