0

我在 Java 中有一个 SSLServerSocket,当客户端连接时,我为其通信创建一个线程:

    System.setProperty("javax.net.ssl.keyStore", "keystore");
    System.setProperty("javax.net.ssl.keyStorePassword", "password");

    SSLServerSocket server = (SSLServerSocket)null;

    if(ipSocket == null){
        ipSocket = new HashMap<String,java.net.Socket>();
    }

    try {

        SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        server = (SSLServerSocket) sslserversocketfactory.createServerSocket(4380);
        log.info("Server started");

    } catch(IOException e) {
        e.printStackTrace();
    }

    while(true){

        try {
            SSLSocket client = (SSLSocket) server.accept();
            log.info("new client");

        } catch (Exception e){
            e.printStackTrace();
        }
    }

问题是代码有时会拒绝连接。它发生在代码运行一段时间时,所以我认为问题是客户端失去了连接并重新连接,但之前的线程仍然存在,并且有一个最大值 SSLServerSockets。

这会发生吗?最大数是多少?

发生断开连接时如何杀死线程?

4

1 回答 1

0

根据您的代码和我对网络的理解(从较低级别和 API 级别),您可能错误地使用了 API。

在高层次上,您希望以不同的方式执行此操作

public static void main(String[] args) {
    System.setProperty("javax.net.ssl.keyStore", "keystore");
    System.setProperty("javax.net.ssl.keyStorePassword", "password");
    SSLServerSocket server = (SSLServerSocket)null;
    if(ipSocket == null){
        ipSocket = new HashMap<String,java.net.Socket>();
    }

    try {
        SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        // Creates a socket with a default backlog of 50 - meaning
        // There will be a maximum of 50 client connection attempts on this 
        // socket after-which connections will be refused. If the server is
        // overwhelmed by more than that number of requests before they can be
        // accepted, they will be refused
        // The API allows for you to speccify a backlog.
        server = (SSLServerSocket) sslserversocketfactory.createServerSocket(4380);
        log.info("Server started");
    } catch(IOException e) {
        e.printStackTrace();
    }

    while(true){
        try {
            // This will take one of the waiting connections
            SSLSocket client = (SSLSocket) server.accept();
            log.info("new client");
            // HERE is where you should create a thread to execute the
            // conversation with the client.
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

我希望更正确地回答你的问题。

关于 EJP 的评论 - 我已经更新了我的解释并引用了位于此处的文档:

传入连接指示(连接请求)的最大队列长度设置为 backlog 参数。如果队列满时有连接指示到达,则拒绝连接。

于 2013-06-03T10:34:56.130 回答