WebSocket连接到...失败:WebSocket握手期间出错:意外响应代码:200

时间:2016-07-26 09:44:17

标签: javascript websocket glassfish-4.1

我正在尝试在Chrome浏览器和Glassfish 4.1.1服务器之间创建websocket连接。不幸的是,我收到HTTP 200消息而不是101.

Chrome DevTool日志:

"WebSocket connection to 'ws://DOMAIN_NAME:8080/serverendpointdemo/' failed: 
Error during WebSocket handshake: Unexpected response code: 200"

客户端代码:

var ws = new WebSocket ("ws://" + document.location.host + "/serverendpointdemo/");

服务器端代码:

package com.za.tutorial.websocket;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/home/USER_NAME/glassfish4/glassfish/domains/domain1/applications/serverendpointdemo")
public class ServerEndpointDemo {
    @OnOpen
    public void handleOpen() {
        System.out.println("Client is now connected...");
    }

    @OnMessage
    public String handleMessage (String message) {
       return null;
    }

    @OnClose
    public void handleClose () {
    }

    @OnError
    public void handleError (Throwable t) {
        t.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

服务器端: @ServerEndpoint(value =“/ ws”) 公共类WebSocketConfig {

private String message = "";
private String to = "";
private String from = "";
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

@OnOpen
public void onOpen(Session session, EndpointConfig econfig) throws IOException {        
    System.out.println("New Web Socket Connection created");
    session.getBasicRemote().sendText("onOpen new socket connection");             
}

@OnClose
public void onClose(Session session) {     
        sessions.remove(session);
}

@OnMessage
public void onMessage(String message, Session session) throws IOException {

}

客户方:

在建立连接时,您应该指定contextpath var ws = new WebSocket(“ws://”+ document.location.host +“/”+ your-contextPathName +“/ serverendpointdemo /”);

http:ws:// hostname:port / contextpath / serverendpoint https:wss:// hostname:port / contextpath / serverendpoint

例如: WS://document.location.host+ “/ WebsocketDemo / WS”;