@Override public void run() { try { // loop endlessly waiting for client connections while (true) { if (!streamsOpen) { // wait for a connection request socket = ss.accept(); gui.setTextArea1("Connected to QD on port " + port, Color.ORANGE); gui.setLabel("Connected to QD on port " + port, Color.GREEN); log.writeToLog("Connected to QD on port " + port); openStreams(); setConnected(); processClientRequests(); } else { gui.setTextArea1("Streams already open on port" + port, Color.ORANGE); gui.setLabel("Streams already open on port " + port, Color.GREEN); log.writeToLog("Streams already open on port " + port); closeStreams(); } } } catch (IOException e) { gui.setLabel("Trouble with accepting Socket on port " + port + ": " + e, Color.RED); gui.setTextArea1("Trouble with accepting Socket on port " + port, Color.ORANGE); log.writeToLog("Trouble with accepting Socket on port " + port); closeStreams(); } }
// Constructor public ServerListener(String portNumber, MSeriesGUI theGui) // Start Constructor { gui = theGui; port = Integer.parseInt(portNumber); streamsOpen = false; printerName = gui.getPrinterName(); log = new MLogs(gui, printerName); log.createLogFile(); // establish a ServerSocket try { ss = new ServerSocket(port); gui.setTextArea1("Waiting for connection ... ", Color.ORANGE); log.writeToLog("Waiting for connection ... "); } catch (BindException b) { gui.setLabel("Port " + port + " already in use", Color.RED); gui.setTextArea1("Port " + port + " already in use", Color.ORANGE); log.writeToLog("Port " + port + " already in use"); closeStreams(); } catch (IOException e) { gui.setLabel("Trouble with ServerSocket creation on port " + port + ": " + e, Color.RED); gui.setTextArea1("Trouble with ServerSocket creation on port " + port, Color.ORANGE); log.writeToLog("Trouble with ServerSocket creation on port " + port); } } // End constructor
public void closeStreams() { try { if (getStreamsOpen()) { toClient.close(); os.close(); fromClient.close(); is.close(); gui.setLabel("...Streams closed down", Color.RED); log.writeToLog("...Streams closed down"); streamsOpen = false; socket.close(); setDisconnected(); } } catch (IOException e) { gui.setLabel("Could not close streams", Color.RED); gui.setTextArea1("Could not close streams", Color.ORANGE); log.writeToLog("Could not close streams"); } }