我在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。
这会发生吗?最大数字是多少?
如何在断开连接时终止线程?
答案 0 :(得分: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的评论 - 我更新了我的解释并引用了位于here的文档:
传入连接指示的最大队列长度(连接请求)设置为backlog参数。如果队列已满时连接指示到达,则拒绝连接。