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 ReadCallback(IAsyncResult ar) { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString().Remove(0, 2); // if (content.IndexOf("<EOF>") > -1) // { // All the data has been read from the // client. Display it on the console. string message = "Read " + content.Length + "bytes from wifi socket. Data = " + content; _screenWriterCall(message); //callJSONParse ParseJson parseJson = new ParseJson(_videoFormActionDelegate, _imageFormActionDelegate); JsonReturn = parseJson.InitialParsing(content); //parse message //put in delegates here to get the proper jsonreturn Send(handler, JsonReturn); // } /* else { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } */ } }