如何在Java中接收SSL套接字数据?

时间:2018-09-16 01:33:59

标签: java sockets ssl

所以我刚刚读了this帖子,它说您需要制作一个如下的SSL套接字:

SocketFactory factory = SSLSocketFactory.getDefault();
Socket socket = factory.createSocket("computerName", 2282);

因此,我认为这不太可行,因为它似乎太简单了,但实际上并没有引发错误。它确实连接到了我的服务器,该服务器目前仅使用普通的套接字连接,但是它从不显示它从服务器接收数据,而只是表明它已连接。这是每个代码:

客户

SocketFactory factory = SSLSocketFactory.getDefault();
Socket socket = factory.createSocket("computerName", 2282);
DataOutputStream outputData = new DataOutputStream(socket.getOutputStream());
outputData.writeUTF("1"));
DataInputStream inputData = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String returnData = inputData.readUTF();

服务器:

Socket socket = server.accept();
DataInputStream inputData = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
DataOutputStream outputData = new DataOutputStream(socket.getOutputStream());
String incomingData = inputData.readUTF();
System.out.println("Received: " + incomingData);
String[] receivedDataArray = incomingData.split("\\s+");
// "1" occurs when the client pings the server.
if (receivedDataArray[0].equals("1"))
    outputData.writeUTF("1");

有什么主意为什么会这样,以及如何解决?

1 个答案:

答案 0 :(得分:0)

它不起作用。由于您没有使用SSLServerSocketFactory创建服务器套接字。建立安全连接之前,应首先设置以下几项内容,例如CIpherSuite TLS版本等。

要设置安全参数,需要创建SSLContext,然后创建服务器套接字

 SSLContext sc = SSLContext.getInstance("TLSv1.3");
    sc.init(null, trustAllCerts, new SecureRandom());
    SSLServerSocket ssl = (SSLServerSocket) sc.getServerSocketFactory().createServerSocket(
            YOURPORTNUMBER);

还有一件事,您的IdentityStore和trustStore应该正确配置。