Search code examples
javamultithreadingserversocket

Continuous running java socket server thread exit on second run


I have a java socket client application that send data through TCP over Socket. The data it send is byte array and can send inconsistent data within inconsistent time interval. Although data send at a particular time will be complete in itself and will not have any marker for end of message. Code for client cannot be modified. I had to create a running thread for server so that it will read data whenever it is available on socket.

Server application work as - Another class create server socket and start thread for incoming message. Incoming message thread read for message on socket passed while initializing the thread. The code has following issues.

1) It reads only the first data sent from client and thread exits on attempting to read second run
2) Cannot use thread to wait for some time period as data can be sent from client in any time interval
3) Cannot try opening and closing socket as another thread on server application will send data to client at any time interval.
4) Do not want code that will block execution of complete application as another thread of this application will be sending data to client through same socket.

Please help and let me know for any further information. Code as below :

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class IncomingMsg extends Thread  {

InputStream in =null;
private Socket clientSocket =null;

public IncomingMsg(Socket clientSoc){
    this.start();
    clientSocket = clientSoc;
}
public void run(){
    try {
        in = clientSocket.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    while (true) {
        try {
            byte[] data = new byte[100];
            int count = in.read(data); //this is where thread exits on second run as new message may not have been received by the time execution reaches this point.
            String message = "";
            if(count>0)
            {

        for(int num=0;num<count;num++)
        {message = message + " "+ data[num];}
System.out.println("Received Message from IP:"+clientSocket.getInetAddress()+" Message Byte:" +message);
            }
            data=null;
        } catch (Exception e) {
            logger.error(this.getClass().getName()+ ": Exception in receiving message "+ e);
}}} }

Solution

  • There was no issue with the given code. Problem was client application changes local port if it does not receive any message. Since server application is not sending any message, local port of client increment and thus server cannot read data on the second run. Will update answer more if any further clue is received.