void Server1() { //... Guid serviceClass; serviceClass = BluetoothService.SerialPort; // - or - etc // serviceClass = MyConsts.MyServiceUuid // var lsnr = new BluetoothListener(serviceClass); lsnr.Start(); // Now accept new connections, perhaps using the thread pool to handle each BluetoothClient conn = lsnr.AcceptBluetoothClient(); Stream peerStream = conn.GetStream(); ///... // etc conn = lsnr.AcceptBluetoothClient(); peerStream = conn.GetStream(); //... }
public void 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"); } } }
} // 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(); } } } //
/// <summary> /// Listeners the accept bluetooth client. /// </summary> /// <param name="token"> /// The token. /// </param> private void Listener(CancellationTokenSource token) { while (true) { if (token.IsCancellationRequested) { return; } using (BluetoothClient client = _listener.AcceptBluetoothClient()) { var streamwriter = client.GetStream(); try { byte[] bufferIn = new byte[1024]; streamwriter.Read(bufferIn, 0, bufferIn.Length); string result = Encoding.UTF8.GetString(bufferIn); var bufferOut = Encoding.UTF8.GetBytes(_commands.GetMessage(result.Replace("\0", ""))); streamwriter.Write(bufferOut, 0, bufferOut.Length); streamwriter.Flush(); } finally { streamwriter.Close(); client.Close(); } } } }
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"); } } }
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); } } }
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é!"); } }
/// <summary> /// Listeners the accept bluetooth client. /// </summary> /// <param name="token"> /// The token. /// </param> private void Listener(CancellationTokenSource token) { using (var client = _listener.AcceptBluetoothClient()) { while (true) { if (token.IsCancellationRequested) { return; } try { var br = new BinaryReader(client.GetStream()); SensorData sensorData = new SensorData { Type = (char)br.ReadByte() }; for (int i = 0; i < 3; i++) { var bytes = br.ReadBytes(4); Array.Reverse(bytes); sensorData.Data[i] = BitConverter.ToSingle(bytes, 0); } _responseAction(sensorData); } catch (IOException) { client.Close(); break; } } } }
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(); }
public void AcceptAndListen() { while (true) { if (isConnected) { try { ReceiveMessages(); }catch (Exception e) { isConnected = btClient.Connected; Console.WriteLine(e.Message); } } else { //TODO: if there is no connection // accepting try{ btListener = new BluetoothListener(BluetoothService.RFCommProtocol); Console.WriteLine(BluetoothService.RFCommProtocol); btListener.Start(); btClient = btListener.AcceptBluetoothClient(); isConnected = btClient.Connected; Console.WriteLine("연결완료"); }catch (Exception) { } } } }
public void readInfoClient() { bluetoothClient = bluetoothListener.AcceptBluetoothClient(); Console.WriteLine("Cliente Conectado!"); Stream stream = bluetoothClient.GetStream(); while (bluetoothClient.Connected) { try { byte[] byteReceived = new byte[1024]; int read = stream.Read(byteReceived, 0, byteReceived.Length); if (read > 0) { Console.WriteLine("Messagem Recebida: " + Encoding.ASCII.GetString(byteReceived) + System.Environment.NewLine); } stream.Flush(); } catch (Exception e) { Console.WriteLine("Erro: " + e.ToString()); } } stream.Close(); }
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 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 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 } }
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); } }
// Hilo que mantiene el servicio Bluetooth public void runBluetooth() { do { try { BluetoothClient client = btListener.AcceptBluetoothClient(); // Acepta conexión con un cliente StreamReader sr = new StreamReader(client.GetStream(), Encoding.UTF8); string clientData = ""; while (true) { string aux = sr.ReadLine(); clientData += aux; if (aux.Equals("</Profile>")) { break; // Recibe XML con los datos del perfil del cliente } } manager = JourneyManager.Instance; string recommendation = manager.ClientManager.manageNFCClient(clientData.Substring(2)); StreamWriter sw = new StreamWriter(client.GetStream(), Encoding.ASCII); sw.Write(Convert.ToString(recommendation)); // Se le envía recomendación personalizada sw.Flush(); sw.Close(); sr.Close(); client.Close(); // Da por finalizada la comunicación con el cliente } catch (Exception e) { } } while (!exit); }
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; } } } }
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"); } } }
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 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."); }
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."); }
private string receiveMessage(int BufferLen) { int bytesRead = 0; BluetoothClient client = null; System.IO.Stream stream = null; byte[,] Buffer; try { client = btListener.AcceptBluetoothClient(); // blocking call stream = client.GetStream(); bytesRead = stream.Read(Buffer, 0, BufferLen); str = (client.RemoteMachineName + ("->" + (System.Text.Encoding.Unicode.GetString(Buffer, 0, bytesRead) + "\r\n"))); } catch (Exception e) { // dont display error if we are ending the listener if (listening) { MsgBox("Error listening to incoming message"); } } finally { if (!(stream == null)) { stream.Close(); } if (!(client == null)) { client.Close(); } } return(str); }
// Hilo que mantiene el servicio Bluetooth public void runBluetooth() { do { try { BluetoothClient client = btListener.AcceptBluetoothClient(); // Acepta conexión con un cliente StreamReader sr = new StreamReader(client.GetStream(), Encoding.UTF8); string clientData = ""; while (true) { string line = sr.ReadLine(); clientData += line; if (line.Equals("</ClientOrder>")) { break; // Recibe XML con los datos del pedido del cliente } } manager = JourneyManager.Instance; string reply = manager.OrdersManager.manageNFCOrder(clientData.Substring(2)); StreamWriter sw = new StreamWriter(client.GetStream(), Encoding.ASCII); sw.Write(Convert.ToString(reply)); // Envío de la respuesta calculada sw.Flush(); sw.Close(); sr.Close(); client.Close(); // Da por finalizada la comunicación con el cliente } catch (Exception e) { } } while (!exit); }
private void ListenLoop() { while (listening) { try { client = listener.AcceptBluetoothClient(); stream = client.GetStream(); SIGN_STREAMSETUP = true; listening = false; // 远程连接后,启动发送文件进程 // 远程设备连接后,启动recieve程序 receiving = true; receiveThread.Start(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); continue; } } }
public ObexListenerContext GetContext() { if (!listening) { throw new InvalidOperationException("Listener not started"); } try { SocketClientAdapter s; switch (transport) { case ObexTransport.Bluetooth: s = new SocketClientAdapter(bListener.AcceptBluetoothClient()); break; case ObexTransport.IrDA: #if NO_IRDA throw new NotSupportedException("No IrDA on this platform."); #else s = new SocketClientAdapter(iListener.AcceptIrDAClient()); break; #endif default: s = new SocketClientAdapter(tListener.AcceptTcpClient()); break; } Debug.WriteLine(s.GetHashCode().ToString("X8") + ": Accepted", "ObexListener"); return(new ObexListenerContext(s)); } catch { return(null); } }
public void ServerConnectThread() { serverStarted = true; updateUI("TAG: ServerConnectThread Message: server started,waiting for clients"); BluetoothListener blueListener = new BluetoothListener(mUUID); blueListener.Start(); updateUI("TAG: ServerConnectThread Message:Client has connected"); while (true) { BluetoothClient conn = blueListener.AcceptBluetoothClient(); Stream mStream = conn.GetStream(); try { //handle server connection byte[] received = new byte[1024]; mStream.Read(received, 0, received.Length); updateUI(Encoding.UTF8.GetString(received)); } catch (IOException e) { updateUI("TAG: ServerConnectedThread Message : Program catch a some error: " + e.Message); } } }
public 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!!!"); } } }
}//Form1_Load private void ListenLoop() { byte[] buffer = new byte[4]; int received = 0; while (listening) { BluetoothClient bc; System.IO.Stream ns; try { bc = lsnr.AcceptBluetoothClient(); ns = bc.GetStream(); } catch { break; } //keep connection open while (listening) { try { byte[] wbuffer = StrToByteArray("hi"); ns.Write(wbuffer, 0, wbuffer.Length); received = ns.Read(buffer, 0, buffer.Length); } catch { break; } if (received > 0) { //string command = ""; int keycode = (int)BitConverter.ToInt16(buffer, 0); String s = textBox1.Text; SetText(s + "\n" + keycode); } else { //connection lost break; } } try { bc.Close(); } catch { } } }//listenloop
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 TryGetClient(object sender, ElapsedEventArgs e) { if (this.listener.Pending()) { this.clientGetter.Enabled = false; this.client = listener.AcceptBluetoothClient(); this.stream = client.GetStream(); this.isConnected = true; GlobalAppEvents.RaiseConnectedEvent(this, new EventArgs()); } }