gpt4 book ai didi

Java SSL 套接字不工作

转载 作者:行者123 更新时间:2023-11-30 11:42:18 26 4
gpt4 key购买 nike

我正在使用 TCP/IP 套接字来创建客户端和服务器应用程序。最初我使用的是常规套接字,但现在我决定使用 SSL 进行连接。我已经创建了一个 keystore 并尝试运行我的应用程序,但它尚未成功。

这是我的服务器代码

public class ArFileServer {

public static void main(String[] args)
{
boolean listening = true;
ServerSocketFactory serversocketfactory;
ServerSocket serverSocket;

try
{
//serverSocket = new ServerSocket(4445);

serversocketfactory = SSLServerSocketFactory.getDefault();
serverSocket = serversocketfactory.createServerSocket(4445);

String keystore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(keystore);

// infinite loop to continually listen for connection requests made by clients
while (listening)
{
new ClientConnection(serverSocket.accept()).start();

if (serverSocket != null)
{
System.out.println("Connection to client established");
}
}

serverSocket.close();
}
catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}
}
}

这是客户端代码:

public class ClientSocket 
{
SocketFactory socketfactory = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;


// establish a connection to All Care's server application through socket 4444 (adjust localhost to reflect the IP address that the server
// is being run from)
public ClientSocket()
{
try
{
//clientSocket = new Socket("localhost", 4445);

//SocketFactory socketfactory = SSLSocketFactory.getDefault();
clientSocket = socketfactory.createSocket("192.168.1.8", 4445);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String truststore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(truststore);
}
catch (IOException e)
{
System.out.println("Could not connect to All Care Server Application : " + e.getMessage());
}
}
}

我也在使用这些运行时参数:

-Djavax.net.ssl.keyStore=C:\Users\Chris\Documents\NetBeansProjects\ArFile\keystore.jks -Djavax.net.ssl.keyStorePassword=password

当我尝试打印信任库时,它总是返回 null,我做错了什么?

最佳答案

When I try to print out the truststore it always returns null

因为你从来没有设置过它。您所做的只是打印出系统属性的值。如果你没有设置它,它就是空的。

what am I doing wrong?

除了打印无意义的信息外,还没有。但是您的大部分代码都没有意义:

if (serverSocket != null)
{
System.out.println("Connection to client established");
}

serverSocket 非空 (a) 在这一点上是不可避免的,并且 (b) 与正在建立的客户端套接字没有任何关系,这在这一点上是不可避免的。

catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}

此时的 IOException 可能意味着很多事情,但它并不意味着“无法创建到端口的套接字连接”。 客户端 进行连接:服务器接受 连接。当您捕获到异常时,请始终打印它的消息,不要自己编造。

关于Java SSL 套接字不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com