WebSocket在打开连接时获得404

时间:2015-03-27 19:16:36

标签: java javascript jsp tomcat websocket

我正在跑步:

  • Tomcat 7
  • Java版本1.8
  • Chrome浏览器版本41.0.2272.89 m

我正在尝试让我的websocket工作,但出于某种原因,我在尝试访问套接字时获得了404(In chrome)。

WebSocket connection to 'ws://localhost:8080/InfiniteCloud/WebSocketExchange' failed: Error during WebSocket handshake: Unexpected response code: 404

尝试打开连接时发生错误。我从这个论坛上查了很多以前的问题,但没有一个问题有效。这是我的服务器端代码:

package websocket;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

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

import org.json.simple.JSONObject;

@ServerEndpoint( value = "/ClientDataExchange")
public class WebSocketExchange {

    static Set<Session> _users = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void handleOpen(Session userSession){
        _users.add(userSession);
    }

    @OnMessage
    public void handleMessage(String message, Session userSession){
        try{

            if(userSession.getUserProperties().get("username") == null){
                userSession.getUserProperties().put("username", message);
                userSession.getBasicRemote().sendText( newUserJSONResponse(message) );
            }
            System.out.println("Message: " + message);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @OnClose
    public void handleClose(Session userSession){
        _users.remove(userSession);
    }

    public String newUserJSONResponse(String username){
        JSONObject j = new JSONObject();
        j.put("ICmessage", "You are now connected as: " + username);

        return j.toJSONString();
    }
}

客户端代码:

var websocket = null;

function sendMessage(){
    websocket.send("Justin");
}

function testWebSocket(){
    var url = "ws://" + document.location.host + document.location.pathname + "WebSocketExchange";

    websocket = new WebSocket(url);

    websocket.onopen = function(){
        console.log("Connected to: " + url);
    }

    websocket.onmessage = function processMessage(message){

        var jsonData = JSON.parse(message.data);

        if(jsonData.message != null){
            console.log(jsonData.message);
        }else{
            console.log("Empty message...");
        }
    }

    websocket.onclose = function(){
        console.log("Closing connection to: " + url);
    }
}

1 个答案:

答案 0 :(得分:0)

您的路径似乎不匹配。在服务器上你有

@ServerEndpoint( value = "/ClientDataExchange")

在客户端上你有

var url = "ws://" + document.location.host + document.location.pathname + "WebSocketExchange";