考虑以下代码,用于非 SSL 套接字服务器和客户端都在一个线程上:
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerClient {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(0); // open a random free port.
Socket c = new Socket(ss.getInetAddress(), ss.getLocalPort());
Socket s = ss.accept();
final byte[] bytes = "Hello World!".getBytes();
final OutputStream out = c.getOutputStream();
System.out.println("writing to stream");
out.write(bytes.length);
out.write(bytes);
System.out.println("reading from stream");
final DataInputStream in = new DataInputStream(s.getInputStream());
int len = in.read();
final byte[] b = new byte[len];
in.readFully(b);
System.out.println(new String(b));
c.close();
ss.close();
}
}
这会产生以下输出:
writing to stream
reading from stream
Hello World!
这个过程打开了一个服务器套接字 - 与一个客户端套接字连接。将数据传递到套接字然后关闭。传递数据没有问题。
考虑一个版本来证明 SSL 套接字:
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Logger;
public class SSLServerClient {
private static Logger log = Logger.getLogger("InfoLogging");
public static void main(String[] args) throws IOException {
System.setProperty("javax.net.ssl.keyStore", "/path/KeyStore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket serverListeningSSLSocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(4380);
log.info("Server started");
SSLSocketFactory sslSocketFactory=(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket clientSocket = (SSLSocket) sslSocketFactory.createSocket(serverListeningSSLSocket.getInetAddress(),
serverListeningSSLSocket.getLocalPort());
SSLSocket serverCommsSSLSocket = (SSLSocket) serverListeningSSLSocket.accept();
log.info("new client");
final byte[] bytes = "Hello World!".getBytes();
final OutputStream out = clientSocket.getOutputStream();
System.out.println("writing to stream");
out.write(bytes.length);
out.write(bytes);
System.out.println("reading from stream");
final DataInputStream in = new DataInputStream(serverCommsSSLSocket.getInputStream());
int len = in.read();
final byte[] b = new byte[len];
in.readFully(b);
System.out.println(new String(b));
clientSocket.close();
serverCommsSSLSocket.close();
serverListeningSSLSocket.close();
}
}
这给出了以下输出:
Nov 21, 2018 10:23:51 PM com.gamble.ssl.SSLServerClient main INFO: Server started
Nov 21, 2018 10:23:52 PM com.gamble.ssl.SSLServerClient main INFO: new client
writing to stream
即它在服务器套接字启动时阻塞。
我的问题是:为什么 Java 中的 SSL 服务器套接字连接会阻塞,而非 SSL 服务器套接字却不会?