javasocket:等待接受的客户端服务器

yshpjwxd  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(249)

我有一个线程池,最多支持3个线程。每个人创建并接受一个客户机。当第四个客户机尝试连接时,我希望通知它必须等待线程/连接空闲。
问题是,当第四个客户机用connect()启动请求时,理论上它会被卡住5亿次,然后打印异常超时字符串,最后再试一次,直到服务器线程可以为它提供服务为止。实际上,客户机传递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>
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题