我开发了一个聊天服务器和客户端Sockets
,一切都很好,直到我在网上某处读到普通Socket
通信容易受到攻击。谷歌搜索了一段时间后,我发现了这个页面,其中显示了一个示例SSLServerSocket
和SSLSocket
实现(下面的代码)。
如果我按照以下代码中的步骤操作,我想知道我的服务器和客户端之间的通信是否安全。
服务器代码
class EchoServer {
public static void main(String[] args) throws IOException {
SSLServerSocket sslServerSocket = null;
try {
SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.println(inputLine);
}
} finally {
if (sslServerSocket != null) {
try {
sslServerSocket.close();
} catch (IOException x) {
// handle error
}
}
}
}
}
客户代码
class EchoClient {
public static void main(String[] args) throws IOException {
SSLSocket sslSocket = null;
try {
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
} finally {
if (sslSocket != null) {
try {
sslSocket.close();
} catch (IOException x) {
// handle error
}
}
}
}
}