Problem in Thread synchronization for sockets in Java Android

133 Views Asked by At

I am writing two types of packets to a PLC which responds by sending different packets for each type of input packets. I am using socket class with two different threads to achieve this i.e. one thread to handle one type of message. Since received messages/packets at sockets can come at any thread it is getting difficult to synchronize and achieve the necessary task.

There are two types of byte data that needs to be send to the PLC socket i.e. ByteFrame1 and ByteFrame2. After sending the packets different responses are received.

Following code snippet shows Thread 1.

Thread workerThread1 = new Thread() {
      @Override
      public void run() {
      try {
            dos = new DataOutputStream(socket.getOutputStream());
            while (socket.isConnected()) {
                dos.write(ByteFrame1);
                 try {
                       DataInputStream dis = new DataInputStream(socket.getInputStream());
                       readLength = dis.read(OutputBytes1, 0, receiveBufferSize1);
                       //Interpret OutputBytes1 code follows

Similarly code snippet for second thread is as follows:

 Thread workerThread2 = new Thread() {
      @Override
      public void run() {
       try {
           dos = new DataOutputStream(socket.getOutputStream());
            while (socket.isConnected()) {
                dos.write(ByteFrame2);
                 try {
                       DataInputStream dis = new DataInputStream(socket.getInputStream());
                       readLength = dis.read(OutputBytes2, 0, receiveBufferSize2);
                       //Interpret OutputBytes2 code follows

I found that both threads are receiving some garbled data that is difficult to interpret. Probable reason can be socket receive getting out of synch due to threads out of order execution. How to achieve synchronization at each thread so that the response received at each thread don't gets mixed up?

1

There are 1 best solutions below

2
ControlAltDel On

Okay a couple of things here.

  1. You should only ever have 1 thread sending messages through a socket. If you have more, you risk gabling one message by adding another message inside it. You can use a queue to send messages sequentially.

  2. Do NOT use Data streams! This is Java-only and now many years beyond its reason d'etre (it was created as a solution to the big/small endian issue - which is no longer an issue)

  3. You should put together a message standard for your communications ala how an HTTP header has information about what is being sent. I recommend using XML or JSON to structure your messages (it's how I do it over Sockets and WebSockets).