I have problems with sockets in java. I have ServerSocketone that listens for accept () and spawns threads for every client request. Communication between clients and server is working fine. I use the input stream to read data from clients in serverthreads, for example:
inputStream = mySocket.getInputStream();
bytes = inputStream.read(buffer);
My problem is that if I call socket.close () from clients, nothing happens with a blocking call bytes = inputStream.read(buffer);, it continues to block. But it works, if I close the socket from the server, then the inputStream.read(buffer);client returns "-1".
SERVER-MAINTHREAD:
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (listening){
new ServerThread(serverSocket.accept(), monitor).start();
}
Server CLIENTTHREADS:
public class ServerThread extends Thread{
public ServerThread(Socket socket, Monitor monitor) {
this.socket = socket;
this.monitor = monitor;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
InputStream inputStream = socket.getInputStream();
monitor.doStuffWithOtherThreads(Object myObject);
bytes = inputStream.read(buffer);
if (bytes == -1){
System.out.println("breaks");
break;
}
byte[] readBuf = (byte[]) buffer;
String readMessage = new String(readBuf, 0, bytes);
System.out.println(readMessage);
System.out.println(bytes);
} catch (IOException e) {
System.out.println("Connection closed");
break;
}
}
}
CUSTOMER:
InetAddress serverAddr = InetAddress.getByName("serverhostname");
socket = new Socket(serverAddr, PORT);
socket.close();