我创建了一个简单的例子来说明我正在尝试做的事情。
我有这样的服务器代码:
package com.company;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class EchoServer {
public
static
void
main(String[] arstring) {
try {
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =
(SSLServerSocket) sslserversocketfactory.createServerSocket(9999);
SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println(string);
System.out.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
客户端代码是这样的:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="utf-8">
<script type="text/javascript">
function onClick(){
var wrc_socket = new WebSocket('wss://localhost:9999');
wrc_socket.onmessage = function(event) {
alert('message = '+event.data);
};
wrc_socket.onclose = function(event) {
alert('Socket is close!');
};
wrc_socket.onopen = function(event) {
alert('Socket is open!');
};
wrc_socket.send('Hi there!');
alert('Done!');
}
</script>
</head>
<body>
<a href="#" onclick="onClick()">Test!</a>
</body>
</html>
我已经创建了私钥和公钥对,并将其导入到密钥库文件中,如此处所述。
我使用参数运行服务器应用程序:
-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 -Djavax.net.debug=all
当我单击"测试"按钮时,我在 ssl 调试中收到此错误:
main, WRITE: TLSv1.2 Change Cipher Spec, length = 1
[Raw write]: length = 6
0000: 14 03 03 00 01 01 ......
Disconnected from the target VM, address: '127.0.0.1:64118', transport: 'socket'
由于某种原因,连接在握手期间关闭。我无法弄清楚原因,请提供解决方案或一些想法来检查。
最后,我想出了原因是什么。 在生成证书或密钥期间(无论如何...我输入了假定的服务器名称,但在 wss 连接期间,地址是 ip - 因此,不匹配并且握手失败。
结论:确保您的 wss 使用与带有 SSL 的名称相同的 URL。