Routing-Packets-In-A-Network-Overlay / src / main / java / csx55 / overlay / transport / TCPServerThread.java
TCPServerThread.java
Raw
package csx55.overlay.transport;

import java.io.*;
import java.net.*;
import csx55.overlay.node.Node;

/**
 * The server thread used by both registry and the messaging node. Both will craete a
 * server socket when they start and pass an instance of themselves and the server thread
 * to create a server thread. This will simply just block until any new sockets
 * are connected to the server socket using the host name and port number. Whenever
 * a socket is connected, it spawns a thread for the receiver and a class for the sender.
 * These will be used to communicate with that node. For example, if a messaging node 
 * creates a socket using the hostname and port specified with the command, this will accept
 * that connection and create a sender and receiver thread to communicate with that socket.
 */
public class TCPServerThread implements Runnable {
    private Node node;
    private ServerSocket serverSocket;

    public TCPServerThread(Node node, ServerSocket serverSocket) {
        this.node = node;
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        while (serverSocket != null) {
            try {
                Socket newSocket = serverSocket.accept();//blocking call to accept new connections

                TCPSenderThread sender = new TCPSenderThread(newSocket);//create a new sender for the new socket
                TCPReceiverThread receiver = new TCPReceiverThread(node, newSocket, sender);//create a new receiver for the new socket
                
                //create and start the receiver thread; it will listen for any new events from the sender in a loop
                Thread threadForReceiver = new Thread(receiver);
                threadForReceiver.start();
                //Sender does not have a run method, so it does not need to be started
            } catch (SocketException se) {
                System.out.println("There was an error with the socket in TCPServerThread");
            } catch (IOException e) {
                System.out.println("There was an error with the IO in TCPServerThread");
                break;
            }
        }
    }
}