即使抛出错误或异常,我也想保持我的套接字服务器打开
这是我的服务器
编辑:
public void serveur()
{
int maxConnectionAllowed=2;
int port=5000;
try{
serveur = new ServerSocket(port);
serveur.setReuseAddress(true);
System.out.println("Waiting for connection");
while (true) {
synchronized (connectedCount) {
while (connectedCount.get() >= maxConnectionAllowed) {
try {
connectedCount.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Socket socket = serveur.accept();
factory.processRequest(socket,connectedCount);
}
}
catch(SocketException sException){
System.err.println("Error when a socket connects");
}
catch(IOException ioException){
System.err.println("Error when reading output/input datas");
}
}
public void run() {
serveur();
}
例如,同时允许的 maxConnection 是 2 ,但是我连接了第三个,抛出异常java.net.ConnectException: Connection refused: connect
并且我的 serversocket 已关闭我希望服务器继续运行,直到有一个地方可用。
编辑:
工厂方法
public void processRequest(Socket socket,AtomicInteger connectedCount) {
try
{
RequestTreatment requestTreatment= new RequestTreatment(socket,connectedCount);
Thread threadWorker= new Thread(requestTreatment);
threadWorker.start();
}
finally
{
compteurConnexion.incrementAndGet();
synchronized (connectedCount) {
connectedCount.notify();
}
}
}
}
请求治疗等级
public RequestTreatment(Socket socket) {
super();
this.socket=socket;
}
@Override
public void run() {
try
{
requestTreatment();
}
finally
{
try {
socket.getInputStream().close();
socket.getOutputStream().close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void treatment() {
try {
in = socket.getInputStream();
out = socket.getOutputStream();
// do stuff
} catch (IOException e) {
e.printStackTrace();
}
}
}
非常感谢