Switch(int num) { numNodes = num; // Initialize listener server socket. REQUIRES PORT 65535 BE OPEN while (true) { try { listener = new ServerSocket(65535); break; } catch (IOException e) { System.err.println("Listener server socket failed to initialize"); continue; } } receivePorts = new ArrayList<Integer>(); sendPorts = new ArrayList<Integer>(); usedPorts = new ArrayList<Integer>(); terminated = 0; // Initialize termination flag termflag = true; // Initialize switching table switchTable = new HashMap<Integer, Integer>(); // Initialize frame buffer buffer = new ArrayDeque<Frame>(); /** * Handles accepting connections, reassigning the connections, and closing connections on * termination */ Thread a = new Thread() { // begin listener thread, reassigns nodes to open ports public void run() { int startingPort = 49153; BufferedWriter writer = null; Socket client; System.out.println("Switch listener beginning loop"); while (termflag) { client = null; try { listener.setSoTimeout(5000); client = listener.accept(); // accept connection System.out.println("Switch connected to client"); writer = new BufferedWriter( new OutputStreamWriter( client.getOutputStream())); // get socket outputStream for (; startingPort < 65534; startingPort++) // iterates until a free port is found { try { ServerSocket tmp = new ServerSocket(startingPort); tmp.close(); if (usedPorts.contains(startingPort)) { throw new IOException(); } System.out.println("Switch reassigning client to " + startingPort); usedPorts.add(startingPort); receivePorts.add(startingPort); break; } catch (IOException e) { System.out.println("Port " + startingPort + " was taken"); continue; } } receiveData(startingPort); // set up new receiver for reassigned connection writer.write(Integer.toString(startingPort) + "\n"); // reassign the client startingPort++; for (; startingPort < 65536; startingPort++) // iterates until a second free port is found { try { ServerSocket tmp = new ServerSocket(startingPort); tmp.close(); if (usedPorts.contains(startingPort)) { throw new IOException(); } usedPorts.add(startingPort); sendPorts.add(startingPort); break; } catch (IOException e) { continue; } } writer.write(Integer.toString(startingPort) + "\n"); startingPort++; writer.close(); client.close(); } catch (SocketTimeoutException e) { System.out.println("Switch timed out in listener"); continue; } catch (IOException e) { System.err.println("Failed to establish reassigned connection to client"); e.printStackTrace(); } } System.out.println("Switch listener is returning"); return; } }; a.start(); sendData(); }