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 java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import gnu.io.*; 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 = clientInputStream.read(clientBuffer); serialPortOutputStream.write(clientBuffer, 0, readFromClient); while ((readFromSerial = serialPortInputStream.read(serialPortBuffer)) != -1) { try { readFromClient = clientInputStream.read(clientBuffer); } 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(); } } } }