在我的主线程中,我有一个while(监听)循环,它在我的ServerSocket对象上调用accept(),然后启动一个新的客户端线程,并在接受新客户端时将其添加到Collection。 但是,while(监听)循环中的accept()调用阻塞,我正在努力关闭连接。请找到我的下面示例代码,有没有办法创建包装器服务来关闭下面服务器端程序的套接字连接。
public static final void serverSocket(IData pipeline) throws ServiceException {
int clientNumber = 0;
ServerSocket listener = null;
int port =0;
Properties socketProperties = new Properties();
try
{
listener = new ServerSocket(port);
System.out.println(listener.getLocalSocketAddress());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while(true){
new Connections(listener.accept(), clientNumber++).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
finally{
try {
listener.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class Connections extends Thread {
private Socket socket;
private int clientNumber;
public Connections(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run()
{
try {
// Send a welcome message to the client.
while (true)
{
// my program
}
catch (IOException e) {
//exception
}
finally {
try {
socket.close();
}
catch (IOException e) {
log.error("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
}
我们非常感谢任何建议。
答案 0 :(得分:0)
你还没有充分描述你想要关闭时的情况。
在任何情况下,您的serverSocket对象都可以成为某些其他线程可用的静态字段,而其他线程可以决定何时关闭。