Socket Monitoring With Java
Java socket objects are used to represent connections between two machines. However, a program using sockets can become bogged down if the program waits for a connection to establish. In this case, you can split off a separate thread of execution that waits for a connection while the main program still runs. By extending this, you can use the separate thread to monitor the sockets for connections and handle them, only notifying the program when a connection is made or another significant even happens.
-
Main ServerSocket Example
-
In order to listen to a port through a socket, create a "SocketServer" object. Socket Servers listen for connections on a specific port. Upon reception of connection information on that port, the Socket Server returns a "Socket" object. Any data received over the connection can be processed through that socket object.
Threads
-
Threads are instances of running code inside a program. These threads of execution allow the concurrent running of code, meaning that code can be written to execute at the same time through different threads. So, for example, a program that wishes to monitor some sort of background state or connection can create a thread which does this, and call the main thread when something changes or a connection occurs.
-
Listening to Ports With Threads
-
By setting up another thread, you can create code that monitors the socket in the background while the main program executes. For example, you could implement a class that extends the "Runnable" class, and run it as a separate thread to run in the background, listening to a port:
private static class SocketListen implements Runnable {
public void run() {
try {
listenSocket = new ServerSocket(9999); //listen to port 9999
} catch (IOException e) {
System.exit(-1); //error
}Socket clientSocket = null;
try {
received = serverSocket.accept(); //connection object if success
} catch (IOException e) {
System.exit(-1); //error
}
}
}
Splitting the Thread
-
If you have defined a runnable class to use as a listening/monitoring agent, all that remains is to use it as a thread. The main program can call a separate thread as part of its execution that will run the socket listening code. Once the code finishes, either due to connection success or error, the monitoring thread rejoins the main thread. The main thread runs a waiting loop until the monitoring thread finishes:
Thread t = new Thread(new SocketListen());
t.start();while (t.isAlive()) {
threadMessage("Still waiting...");
t.join(1000); //waits one second before repeating loop
}
-