I have a program that starts up a passive server that spawns a connection handler for each connection to the server socket. I would like to find an eloquent way to shutdown the server socket and release the port. Currently, I am not sure how to interrupt the Socket.accept
method. I have been using a synchronized method to set a flag in another Thread, but Socket.accpet
blocks until a connection is made.
My passive server code
package NetSecConsole;
import java.io.*;
import java.net.*;
import javax.swing.SwingUtilities;
public class PassiveServer implements Runnable
{
Thread runner;
int port = 20000;
MainFrame mainFrame;
ServerSocket s = null;
public PassiveServer(MainFrame mf, int hostPort)
{
mainFrame = mf;
port = hostPort;
try
{
s = new ServerSocket(hostPort);
}
catch (Exception e)
{
newStatus("Server [Constructor]: Could not open server socket! " + e);
}
}
public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}
@Override
public void run()
{
try
{
int connCount = 1;
for (;;)
{
// Sit and wait for a connection
newStatus("Server [run]: Waiting for connection to port " + Integer.toString(port) + "...");
Socket incomingConnection = s.accept();
// Pass the connection off to a connection handler thread
newStatus("Server [run]: Got connection on port " + Integer.toString(port));
final ConnectionHandler conHand = new ConnectionHandler(mainFrame, incomingConnection, connCount);
// Start the connection handler, then continue;
conHand.start();
connCount++;
}
}
catch (IOException e)
{
newStatus("Server [run]: IOException: " + e);
}
}
public final void newStatus(final String arg)
{
Runnable sendMsg = new Runnable()
{
@Override
public void run()
{
mainFrame.newStatusLine(arg);
}
};
SwingUtilities.invokeLater(sendMsg);
}
}