在我的主線程我有一段時間(聽)循環它調用accept()方法我ServerSocket對象上,然後開始一個新的客戶端線程,並將其添加到集合時,新客戶被接受。 但是,while(listen)循環中的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");
}
}
任何建議將不勝感激。
當'Connections'對象或者完成什麼是應該做的或遇到它使用的插座上EOS或致命'IOException'的連接應該被關閉。例子比比皆是。不清楚問題是什麼。 – EJP