The situation is this: the client and server communicate through a socket. Server with a modem via SerialPort . Both socket and serial-Port have their Input- and OutputStream . On the server, I read from the socket InputStream and thrust it into the OutputStream serial-Port. When a client does socket.close() , how can the server close SerialPort in response to this? Thank.

 package server; import; import; import; import; import*; public class ClientConnection implements Runnable { private SerialPort port = null; private Socket client; private InputStream serialPortInputStream; private OutputStream serialPortOutputStream; private InputStream clientInputStream; private OutputStream clientOutputStream; private boolean isStopWork = false; public ClientConnection(Socket client) { this.client = client; } public void run() { try { port = ModemManager.getFreePort(); } catch (PortInUseException e) { e.printStackTrace(); } try { clientInputStream = client.getInputStream(); clientOutputStream = client.getOutputStream(); serialPortInputStream = port.getInputStream(); serialPortOutputStream = port.getOutputStream(); byte[] clientBuffer = new byte[512]; byte[] serialPortBuffer = new byte[512]; int readFromSerial; int readFromClient; readFromClient =; serialPortOutputStream.write(clientBuffer, 0, readFromClient); while ((readFromSerial = != -1) { try { readFromClient =; } catch (Exception e) { port.close(); } clientOutputStream.write(serialPortBuffer, 0, readFromSerial); } } catch (IOException e) { e.printStackTrace(); } finally { try { clientInputStream.close(); clientOutputStream.close(); serialPortInputStream.close(); serialPortOutputStream.close(); port.close(); client.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } 

    1 answer 1

     try { byte[] buffer = new byte[256]; int rc; while ((rc = != -1) modemOS.write(buffer, 0, rc); } finally { modemOS.close(); fromClientIS.close(); } 
    • I have a slightly different situation. I read in a loop from a modem, not from a client. - vicpro
    • Well, read both directions. When a breakage happens, close everything. The truth will have to poke around with the threads. - cy6erGn0m
    • And how to read in both directions at the same time? I can not understand (( - vicpro
    • I have this job so it goes to Thread. What do I need to create 2 more? One to do? reading socket-> modem, and another modem-> socket? - vicpro pm
    • Why two? One must still be done. But how else to find out that some kind of socket is closed if we are blocking from reading another? There are simply no options. - cy6erGn0m 4:21 pm