I have problems with my program when I need to send strings from my bluetooth socket server to my client bluetooth socket. Everything works fine, while I only send one line at a time (for example, chatting), but if I need to write more lines in a short period of time (to exchange information), the lines will not be separated from the client code, For example, if I send " FirstUser, "and immediately after that," SecondUser, "the client does not read" FirstUser, "and then" SecondUser. " He will read "FirstUserSecondUser". How can I avoid this behavior?
Edit: if I allow Thread sleep before it can send a new message, it reads the correct lines, but this solution does not work fine for my need.
Server code: sending to all clients (edited)
public synchronized void sendToAll(String message) { try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } publishProgress(message); for(OutputStream writer:outputList) { try { writer.write(message.getBytes()); writer.flush(); } catch (IOException e) { System.out.println("Some-Error-Code"); } } }
Server code: reading from client:
public void run() { String nachricht; int numRead; byte[] buffer = new byte[1024]; while (runningFlag) { try { if((numRead = inputStream.read(buffer)) >= 0) { nachricht = new String(buffer, 0, numRead); serverThread.handleMessage(nachricht); } } catch (IOException e) { this.cancel(); e.printStackTrace(); } } }
Client code: read from server (edited)
@Override protected Void doInBackground(Integer... ints) { String nachricht = new String(); byte[] buffer = new byte[1024]; int numRead; while (runningFlag) { try { if(((numRead = inputStream.read(buffer)) >= 0)) { nachricht = new String(buffer, 0, numRead); publishProgress(nachricht); } } catch (IOException e) { clientGame.finish(); e.printStackTrace(); } } return null; }
Client code: write to server
public synchronized void write(String nachricht) { try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } try { outputStream.write(nachricht.getBytes()); outputStream.flush(); } catch (IOException e) { this.cancel(); e.printStackTrace(); } }
I appreciate every little help :).