我尝试将javascript与chrome连接到java jetty服务器。由于使用https,我将不得不使用wss(ws与http工作正常)我使用的密钥库是由我用于https的普通证书创建的,使用java keytools。 这就是我创建服务器的方式:( jetty服务器位于除网站之外的另一个根服务器上)
System.out.println("Setting up jetty server...");
server = new Server(10061);
System.out.println("setting handler..");
System.out.println("configuring ssl support...");
SslContextFactory contexfactory = new SslContextFactory();
contexfactory.setKeyStorePath("/home/keystore");
contexfactory.setKeyStorePassword("********");
contexfactory.setKeyManagerPassword("********");
SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(contexfactory, org.eclipse.jetty.http.HttpVersion.HTTP_1_1.toString());
HttpConfiguration config = new HttpConfiguration();
config.setSecureScheme("https");
config.setSecurePort(10062);
config.setOutputBufferSize(32786);
config.setRequestHeaderSize(8192);
config.setResponseHeaderSize(8192);
HttpConfiguration sslConfig = new HttpConfiguration(config);
sslConfig.addCustomizer(new SecureRequestCustomizer());
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(sslConfig);
connector = new ServerConnector(server, sslConnectionFactory, httpConnectionFactory);
connector.setPort(10062);
server.addConnector(connector);
ServletContextHandler wscontext = new ServletContextHandler(ServletContextHandler.SESSIONS);
wscontext.setContextPath("/");
wscontext.setResourceBase(".");
wscontext.setClassLoader(Thread.currentThread().getContextClassLoader());
wscontext.addServlet(new ServletHolder("cubenex", CubenexServlet.class), "/");
wscontext.setHandler(new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(Handler.class);
}
});
server.setHandler(wscontext);
webServerThread = new Thread(new Runnable() {
public void run() {
try {
server.start();
server.join();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
webServerThread.start();
System.out.println("Jetty server set up!");
} catch (Exception e) {
e.printStackTrace();
}
jetty服务器没有错误,我得到确认2018-02-23 08:21:38.987:INFO:oejs.ServerConnector:Thread-1: Started ServerConnector@6356e82c{SSL-HTTP/1.1}{0.0.0.0:10062}
当我使用以下javascript连接时:
var ws = new WebSocket("wss://***.**.***.**:10062/");
ws.onopen = function(){
ws.send("login "+user+" "+password);
}
ws.onmessage = function(msg){
console.log(msg.data);
}
我收到错误:
WebSocket connection to 'wss://137.74.140.73:10062/' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
答案 0 :(得分:0)
不要混用处理程序和Servlet。
改变......
wscontext.setHandler(new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(Handler.class);
}
});
改为使用Servlet。
String wsPathSpec = "/mypath"; // use "/" if you want here.
wscontext.addServlet(new WebSocketServlet() {
@Override
public void configure(WebSocketServletFactory factory)
{
factory.register(Handler.class);
}
}, wsPathSpec);