我有一个最多可容纳3个线程的线程池。每个人都创建并接受一个客户。当第四个客户端尝试连接时,我希望它被告知必须等待直到线程/连接空闲为止。
问题在于,当第4个客户端使用connect()启动请求时,理论上它应该停留500毫秒,而不是打印异常超时字符串,最后再试一次,直到服务器线程可以为它服务为止。 实际上,客户端会传递connect(),并且当然会卡在ObjectOutputStream中,而不会显示任何错误消息...
客户端:
boolean connected = false;
Socket s=null;
ObjectOutputStream dos = null;
ObjectInputStream dis = null;
while (!connected) {
try {
s = new Socket();
InetSocketAddress sa = new InetSocketAddress("localhost", 5056);
s.connect(sa,500);
connected = true;
dos = new ObjectOutputStream(s.getOutputStream());
dis = new ObjectInputStream(s.getInputStream());
} catch (ConnectException e) {
System.out.println("Error while connecting. " + e.getMessage());
} catch (SocketTimeoutException e) {
System.out.println("Connection: " + e.getMessage() + ".");
} catch (IOException e) {
e.printStackTrace();
}
}
//<CONNECTED: OPERATIONS TO DO>
服务器端:
服务器调度程序:
ServerSocket ss = new ServerSocket(5056);
ExecutorService exec = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) { // only 10 connections in total
Runnable task = new ClientHandler(ss);
exec.execute(task);
}
exec.shutdown();
服务器任务:
class ClientHandler implements Runnable {
final ServerSocket ss;
private Socket s;
private ObjectInputStream dis;
private ObjectOutputStream dos;
// Constructor
public ClientHandler(ServerSocket ss) {
this.ss = ss;
}
@Override
public void run() {
try {
System.out.println("ClientHandler: "+Thread.currentThread().getName()+" <WAITING>");
s = ss.accept();
System.out.println("ClientHandler: "+Thread.currentThread().getName()+" <CONNECTED>");
dis = new ObjectInputStream(s.getInputStream());
dos = new ObjectOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
//<OPERATIONS>
}
}