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(); } } }
void DoTestCreateFails(Guid guid, byte[] sdpRecordGiven, int channelOffset) { byte[] sdpRecord = new byte[sdpRecordGiven.Length]; sdpRecordGiven.CopyTo(sdpRecord, 0); // BluetoothListener lstnr = new InTheHand.Net.Sockets.BluetoothListener(guid, sdpRecord, channelOffset); Assert.Fail("DoTestCreateFails didn't fail!"); }
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 static bool Open(NewMessageDelegate msg) { if (_BtListener == null) { _BtListener = new BluetoothListener(BT_GUID); } _BtListener.Stop(); _BtListener.Start(); _Listen = true; _BtListener.BeginAcceptBluetoothClient(ListenThread, null); 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; }
/// <summary> /// Initializes a new instance of the ObexListener class specifiying the transport to use. /// </summary> public ObexListener(ObexTransport transport) { #if WinCE PlatformVerification.ThrowException(); #endif switch(transport) { case ObexTransport.Bluetooth: ServiceRecord record = CreateServiceRecord(); bListener = new BluetoothListener(BluetoothService.ObexObjectPush, record); bListener.ServiceClass = ServiceClass.ObjectTransfer; break; case ObexTransport.IrDA: iListener = new IrDAListener("OBEX"); break; case ObexTransport.Tcp: tListener = new TcpListener(IPAddress.Any, 650); break; default: throw new ArgumentException("Invalid transport specified"); } this.transport = transport; }
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(); } } }
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 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 Form1_Load(object sender, System.EventArgs e) { setButtonEnabled = new setButtonEnabledHandler(setButtonEnabledMethod); setRcvText = new setTextHandler(setRcvTextMethod); setSendText = new setTextHandler(setSendTextMethod); 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(PANUService); }
/// <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); } } }
void StartListener() { var listener = new BluetoothListener(OurServiceClassId); InfoMessage("Starting listener"); listener.Start(); listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener); InfoMessage("Started listening..."); }
/// <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); }
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; } }
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(); }
internal BTZomBServer(BluetoothListener listener, string from, int tn, BTZomBFingerFactory finger) { listen = listener; this.from = from; severThread = new Thread(ZomBworker); TeamNumber = tn; ff = finger; }
private void disconnectBluetooth() { connected = false; updateUI("Client disconnected"); conn.Close(); conn = null; bluetoothListener.Stop(); bluetoothListener = null; bluetoothServerThread.Abort(); }
/// <summary> /// Create a new ZomB FingerServer Factory /// </summary> /// <param name="teamNumber">Your team number</param> /// <param name="from">Path to saved data folder</param> /// <param name="to">Save data to this folder</param> /// <remarks> /// The path should be a reference to a folder that contains all the data files. /// Once all the files are sent, the tag .ZomBarchiveXXX is appended to their file name, where /// XXX is the time ticks. /// The To path works similarly, but .ZomBYYY is appended before the file extension, where /// YYY is the transfer number stored in the file .ZomB in the To path /// </remarks> internal BTZomBFingerFactory(int teamNumber, string from, string to) { //AutoExtractor.Extract(AutoExtractor.Files.InTheHandManaged | AutoExtractor.Files.InTheHandNative); saveTo = to; pullFrom = from; //team GUID, last part is random, don't want to calculate if (teamgid != null) teamgid = new Guid(teamNumber * teamNumber, (short)teamNumber, (short)teamNumber, new byte[] { 0xa1, 0xfc, 0xf7, 0x95, 0x4a, 0x58, 0x6f, 0x25 }); radio = InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio; listen = new BluetoothListener(teamgid); bserve = new BTZomBServer(listen, pullFrom, teamNumber, this); radio.Mode = RadioMode.Connectable; client = new BluetoothClient(); bfinger = new BTFinger(client, saveTo, teamNumber, this); TeamNumber = teamNumber; }
protected virtual void Dispose(bool disposing) { if (disposing) { try { if (blueListener != null) { blueListener.Stop(); blueListener = null; } } catch (Exception) { } } }
/// <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; }
private void StartListener() { var lsnr = new BluetoothListener(OurServiceClassId); lsnr.ServiceName = OurServiceName; lsnr.Start(); btListener = lsnr; ThreadPool.QueueUserWorkItem(ListenerAccept_Runner, lsnr); }
/// <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; } }
/// <summary> /// The dispose. /// </summary> /// <param name="disposing"> /// The disposing. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_cancelListnerSource != null) { _listener.Stop(); _listener = null; _cancelListnerSource.Cancel(); } } }
public BluetoothServer(Game1 game, BluetoothDevice device) { bluetoothListener = new BluetoothListener(new Guid(GUID_SERVER)); bluetoothDevice = device; }