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(); } } }
public bluetooth(Guid applicationGuid, MainWindow mwObject) { serverSocket = new BluetoothListener(applicationGuid); serverSocket.Start(); serverWorker = new BackgroundWorker(); serverWorker.DoWork += new DoWorkEventHandler(ServerWorker_DoWork); serverWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ServerWorker_RunWorkerCompleted); this.mwObject = mwObject; }
/// <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; }
// With no record pre-parsing this fails in NativeMethods.WSASetService // with error 10022 which we throw as: SocketException : An invalid argument was supplied public void ObexListenerBadTruncated() { // Truncate the record. byte[] record = new byte[ObexListener_ServiceRecord.Length - 10]; Array.Copy(ObexListener_ServiceRecord, 0, record, 0, record.Length); const int dummyOffset = 5; //DoTest(BluetoothService.ObexObjectPush, record, dummyOffset); BluetoothListener lstnr = new InTheHand.Net.Sockets.BluetoothListener(BluetoothService.ObexObjectPush, record, dummyOffset); lstnr.Start(); }
private bool ServisOlustur() { try { istemciDinleyici = new BluetoothListener(servisAdi); istemciDinleyici.Start(); } catch (Exception) { return false; } return true; }
public void StartListening() { BluetoothListener btl = new BluetoothListener(MyService); btl.Start(); listening = true; while (listening) { Console.WriteLine("wait for device"); BluetoothClient conn = btl.AcceptBluetoothClient(); Console.WriteLine("device accepted"); DispatchConnection(conn); } }
public NetworkManager(Guid applicationGuid, MainWindow mwObject) { serverSocket = new BluetoothListener(applicationGuid); serverSocket.Start(); jpgEncoder = GetEncoder(ImageFormat.Jpeg); myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Settings.Default.CompressionLevel); myEncoderParameters.Param[0] = myEncoderParameter; serverWorker = new BackgroundWorker(); serverWorker.DoWork += new DoWorkEventHandler(ServerWorker_DoWork); serverWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ServerWorker_RunWorkerCompleted); this.mwObject = mwObject; }
public void ServerConnectThread() { _screenWriterCallBT("Bluetooth Server started, waiting for clients.."); BluetoothListener blueListener = new BluetoothListener(mUUID); blueListener.Start(); BluetoothClient conn = blueListener.AcceptBluetoothClient(); _screenWriterCallBT("Bluetooth Client has connected"); bool disconnectedClient = false; while (true) { try { if (disconnectedClient) { _screenWriterCallBT("Bluetooth server waiting for client"); conn = blueListener.AcceptBluetoothClient(); disconnectedClient = false; } Stream mStream = conn.GetStream(); byte[] recieved = new byte[1024]; mStream.Read(recieved, 0, recieved.Length); string content = Encoding.ASCII.GetString(recieved).TrimEnd('\0'); if (content.Length == 0) { disconnectedClient = true; } _screenWriterCallBT("Recieved: " + content + "via bluetooth"); ParseJson parseJson = new ParseJson(_videoFormActionDelegate, _imageFormActionDelegate); JsonReturn = parseJson.InitialParsing(content); //parse message byte[] sent = Encoding.ASCII.GetBytes(JsonReturn); mStream.Write(sent, 0, sent.Length); string messageSent = Encoding.ASCII.GetString(sent); _screenWriterCallBT("sent via Bluetooth: " + messageSent); } catch (IOException exception) { _screenWriterCallBT("Bluetooth Client has disconnected. Exception:" + exception + "\n"); } } }
public void start() { try { bluetoothListener = new BluetoothListener(UUID); bluetoothListener.Start(); Console.WriteLine("Aguardando Clientes.."); Thread thread = new Thread(new ThreadStart(readInfoClient)); thread.Start(); } catch (Exception e) { Console.WriteLine("Erro: " + e.ToString()); } }
/// <summary> /// Starts the listening from Senders. /// </summary> /// <param name="reportAction"> /// The report Action. /// </param> public void Start(Action<string> reportAction) { WasStarted = true; _responseAction = reportAction; if (_cancelSource != null && _listener != null) { Dispose(true); } _listener = new BluetoothListener(_serviceClassId) { ServiceName = "MyService" }; _listener.Start(); _cancelSource = new CancellationTokenSource(); Task.Run(() => Listener(_cancelSource)); }
/*public static void md5(string source) { byte[] data = System.Text.Encoding.UTF8.GetBytes(source); MD5 md = MD5.Create(); byte [] cryptoData = md.ComputeHash(data); Console.WriteLine(System.Text.Encoding.UTF8.GetString(cryptoData)); md.Clear(); } */ public void Listen() { try { new BluetoothClient(); } catch (Exception ex) { var msg = "Bluetooth init failed: " + ex; MessageBox.Show(msg); throw new InvalidOperationException(msg, ex); } Bluetoothlistener = new BluetoothListener(OurServiceClassId); Bluetoothlistener.ServiceName = OurServiceName; Bluetoothlistener.Start(); Bluetoothclient = Bluetoothlistener.AcceptBluetoothClient(); byte[] data = new byte[1024]; Ns = Bluetoothclient.GetStream(); Ns.BeginRead(data, 0, data.Length, new AsyncCallback(ReadCallBack), data); DataAvailable(this, "Begin to read"); }
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; }
void DoTest(Guid guid, byte[] sdpRecordGiven, int channelOffset) { byte[] sdpRecord = new byte[sdpRecordGiven.Length]; sdpRecordGiven.CopyTo(sdpRecord, 0); // Assert.AreEqual(0, sdpRecord[channelOffset]); InTheHand.Net.Sockets.BluetoothListener lstnr = null; try { lstnr = new InTheHand.Net.Sockets.BluetoothListener(guid, sdpRecord, channelOffset); Assert.AreEqual(sdpRecord, lstnr.ServiceRecord.ToByteArray()); Assert.AreEqual(sdpRecordGiven, lstnr.ServiceRecord.SourceBytes); lstnr.Start(); int port = lstnr.LocalEndPoint.Port; Assert.AreNotEqual(0, port); sdpRecord[channelOffset] = checked ((byte)port); Assert.AreEqual(sdpRecord, lstnr.ServiceRecord.ToByteArray()); Assert.AreEqual(sdpRecordGiven, lstnr.ServiceRecord.SourceBytes); } finally { if (lstnr != null) { lstnr.Stop(); } } }
void StartListener() { var listener = new BluetoothListener(OurServiceClassId); InfoMessage("Starting listener"); listener.Start(); listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener); InfoMessage("Started listening..."); }
internal void ServerListeningThread() { try { serverStarted = false; // just making sure server start is in sync try { blueListener = new BluetoothListener(mUUID); blueListener.Start(); serverStarted = true; } catch (Exception ex) { serverStarted = false; Log.Unhandled(ex); if (noBlockingMode) { Log.BtServer("Bluetooth enhet er ikke støttet, er slått av, eller mangler." + ex.Message, true); } else { Log.ErrorDialog(ex, "Problem oppstod ved start av Bluetooth listener.\nBluetooth enhet er ikke støttet, er slått av, eller mangler. Kan også oppstå når der er problem med programvaren/driver til Bluetooth maskinvaren.", "Bluetooth serveren kan ikke starte."); } } Log.BtServer("Bluetooth server har startet. Aksepterer tilkoblinger fra alle MScanner mobiler fra versjon " + main.appConfig.blueServerMinimumAcceptedVersion); while (true) { try { if (!serverStarted) break; if (blueListener.Pending()) { using (BluetoothClient client = blueListener.AcceptBluetoothClient()) { ClientConnected(client); } } } catch (SocketException ex) { Log.BtServer("Lese/skrive feil: " + ex.Message); break; } catch (Exception ex) { Log.Unhandled(ex); break; } } if (blueListener != null) blueListener.Stop(); if (blueListener != null) Log.BtServer("Server avslått"); serverStarted = false; } catch (Exception ex) { Log.BtServer("Generell feil: " + ex.Message); } finally { if (blueListener != null) { blueListener.Stop(); blueListener = null; } serverStarted = false; } }
/// <summary> /// Waiting to accept connection with Android. (PC as Slave) /// </summary> /// <param name="listener">Listen requests to accept and connect</param> /// <param name="client">Created from accepted connection</param> /// <returns></returns> private static bool ConnectAndroid(ref BluetoothListener listener, ref BluetoothClient client) { try { listener = new BluetoothListener(BluetoothService.RFCommProtocol); listener.Start(); client = listener.AcceptBluetoothClient(); return true; } catch (Exception) { MessageBox.Show(@"Error. Connection is failed!"); return false; } }
private BluetoothListener StartBluetoothListener() { _logger.Debug("Creating BluetoothListener({0})", _commonSerialBoardServiceId); var listener = new BluetoothListener(_commonSerialBoardServiceId); _logger.Debug("Starting Bluetooth listener..."); listener.Start(); _logger.Debug("Bluetooth listener started."); return listener; }
/// <summary> /// /// </summary> private void StartListener() { _listener = new BluetoothListener(_serviceClassId) { ServiceName = "MyService" }; _listener.Start(); _cancelListnerSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { var status = this.Listener(_cancelListnerSource); this.Stop(); this.OnListnerStopped(status); }); WasStarted = true; }
/// <summary> /// Threaded loop constantly listens for imcoming connections /// </summary> public void ListenLoop() { // create a new bluetooth listener object btListener = new InTheHand.Net.Sockets.BluetoothListener(serviceGUID); // start the listener btListener.Start(); // on exit, run is set to false to terminate all threads while(run) { // Call ReceiveBTData to build a valid Match object from the incoming connection Match m = ReceiveBTData(); //if the data returned is valid if(m!=null) { // if the Match has not already been registered add if (!MainForm.member.MatchExists(m.MACAddress)) { // add the Match into the system MainForm.member.AddMatch(m); } // if they dont have my profile then send it if (!m.HasMyProfile) { // retreive the DeviceAddress object from the MACAddress // loop through all the discovered devices for (int i = 0; i < bTDevices.Length; i++) {//if the MAC address match return the DeviceAddress object if(bTDevices[i].DeviceAddress.ToString()==m.MACAddress) SendBluetoothProfile(bTDevices[i].DeviceAddress, 1); } } // Sleep for 100ms //Thread.Sleep(100); } } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; serviceClass = BluetoothService.SerialPort; var lsnr = new BluetoothListener(serviceClass); lsnr.Start(); worker.ReportProgress(0); conn = lsnr.AcceptBluetoothClient(); worker.ReportProgress(1); connected = true; Stream peerStream = conn.GetStream(); byte[] buf = new byte[1]; while (true) { int readLen = peerStream.Read(buf, 0, buf.Length); string val = ASCIIEncoding.ASCII.GetString(buf); if (readLen == 0) { worker.ReportProgress(2); break; } else { if (dic.ContainsKey(val)) { au3.Send(dic[val]); } /* else { worker.ReportProgress(3); label4.Text = "Please Report: Undefined " + val; } */ } } }
public void ServerConnectThread() { serverStarted = true; updateUI("Server started, waiting for clients"); BluetoothListener blueListener = new BluetoothListener(mUUID); blueListener.Start(); conn = blueListener.AcceptBluetoothClient(); updateUI("Client has connected"); Stream mStream = conn.GetStream(); bool initialized = false; while(true) { try { byte[] received = new byte[1024]; mStream.Read(received, 0, received.Length); updateUI("Received" + Encoding.ASCII.GetString(received)); if (initialized == false) { //parse json here JObject input = JObject.Parse(Encoding.ASCII.GetString(received)); //send updates to vjoy program vjoy.setCoefficient(input); initialized = true; } //Console.WriteLine("recieved: " + received); try { //parse json here JObject payload = JObject.Parse(Encoding.ASCII.GetString(received)); //send updates to vjoy program vjoy.setValues(payload); } catch(JsonReaderException bluetoothError) { Console.WriteLine("BLUETOOTH ERROR: " + bluetoothError.ToString()); } byte[] sent = Encoding.ASCII.GetBytes("Hello World"); mStream.Write(sent, 0, sent.Length); } catch (IOException exception) { updateUI("Client has disconnected"); break; } } }
public void MakeConnection() { BluetoothClient thisRadio = GetRadio(); if (thisRadio == null) { SetError("Bluetooth radio not found"); return; } BluetoothDeviceInfo pulseOx = GetPulseOx(thisRadio); if (pulseOx == null) { SetError("Pulse oximeter not found"); return; } noninEndpoint = new BluetoothEndPoint(pulseOx.DeviceAddress, BluetoothService.SerialPort); /* Listen mode */ if (ATREnabled) { BluetoothListener btListen = new BluetoothListener(BluetoothService.SerialPort); btListen.Start(); noninClient = btListen.AcceptBluetoothClient(); } /* Connect mode */ else { noninClient = new BluetoothClient(); try { noninClient.Connect(noninEndpoint); } catch (SocketException ex) { SetError("Couldn't connect to pulse oximeter", ex); } } if (noninClient.Connected) { connectionBegin = DateTime.Now; } GetMostRecentReading(); }
public void receiveLoop() { string strReceived; btListener = new BluetoothListener(ServiceName); btListener.Start(); strReceived = receiveMessage(MAX_MESSAGE_SIZE); while (listening) { // ---keep on listening for new message if ((strReceived != "")) { this.Invoke(new EventHandler(// TODO: Warning!!!! NULL EXPRESSION DETECTED... .)); strReceived = receiveMessage(MAX_MESSAGE_SIZE); } } }
/// <summary> /// 创建监听线程,监听外围蓝牙设备的连接 /// </summary> private void Listen() { if (radio == null) return; listener = new BluetoothListener(BluetoothService.SerialPort); listener.Start(); listening = true; listenThread = new System.Threading.Thread(ListenLoop); listenThread.Start(); sendfileThread = new System.Threading.Thread(SendFileLoop); sendDataThread = new System.Threading.Thread(SendDataLoop); }
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); } }
private void doListen(object sender, ElapsedEventArgs e) { if (isSlave && !listen) { Bluetoothlistener = new BluetoothListener(BluetoothService.SerialPort); Bluetoothlistener.Start(); localClient = Bluetoothlistener.AcceptBluetoothClient(); isPaired = true; } listen = true; if (localClient != null && localClient.Connected && !stop) { try { byte[] data = new byte[6]; Ns = localClient.GetStream(); Ns.ReadTimeout = 5000; Ns.Read(data, 0, data.Length); listenAttemps = 0; // event message if (onReceiveMessage != null) { Console.WriteLine("RECEIVED " + data); onReceiveMessage.Invoke(ASCIIEncoding.ASCII.GetString(data)); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); listenAttemps++; //Connexion coupé if (onConnectionEnded_Event != null && listenAttemps >= 20) { onConnectionEnded_Event.Invoke("cut"); } } } else if(stop) { Ns.Dispose(); Ns.Close(); closeConnection(); init(macAddr); } else if (!localClient.Connected) { Console.WriteLine("Connection Terminer ou jamais initié"); } }
private void StartListener() { var lsnr = new BluetoothListener(OurServiceClassId); lsnr.ServiceName = OurServiceName; lsnr.Start(); btListener = lsnr; ThreadPool.QueueUserWorkItem(ListenerAccept_Runner, lsnr); }
private void Form1_Load(object sender, System.EventArgs e) { BluetoothRadio br = BluetoothRadio.PrimaryRadio; if (br == null) { MessageBox.Show("No supported Bluetooth radio/stack found."); } 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; } } bl = new BluetoothListener(service); bl.Start(); System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ListenLoop)); t.Start(); }
private void startInputListener() { var lsnr = new BluetoothListener(OurServiceClassId); lsnr.ServiceName = OurServiceName; lsnr.Start(); Thread worker = new Thread(new ParameterizedThreadStart(Listener_Runner)); worker.Name = "InputListener"; worker.IsBackground = true; worker.Start(lsnr); }