Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

tomcat - WebSocket 404 error

I'm trying to implement WebSocket on my site. Following basic tutorials I added this class:

@ServerEndpoint(value="/websocketendpoint")
public class WebSocket {
    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

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

    @OnOpen
    public void onOpen(Session peer){ peers.add(peer); }

    @OnClose
    public void onClose(Session peer){ peers.remove(peer); }
}

And this JS:

var wsUri = "ws://" + document.location.host + document.location.pathname + "websocketendpoint";
var ws = new WebSocket(wsUri);
ws.onopen = function(){
    ws.send("Message to send");
    alert("Message is sent...");
};
ws.onmessage = function (evt){   
    var received_msg = evt.data;
    alert("Message is received...");
};
ws.onclose = function(){ 
    alert("Connection is closed...");
};

I added the js to one of my pages, and only ws.onclose is called, in console I get this error:

Firefox: Firefox can't establish a connection to the server at ws://localhost:8080/Mysite/websocketendpoint

Chrome: Error during WebSocket handshake: Unexpected response code: 404

I tried using 'ws://echo.websocket.org' as wsUri and it works, so I guess the problem is on server side.

I'm using the following libraries: javaee-api-7.0, javax.websocket-api-1.0 My browsers are compatible with websockets (I checked)

Similar topics didn't help me, so I'm asking you for sugestions on how to fix the problem

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might want to check if this is the root of your error: tomcat 7.0.50 java webscoket implementation gives 404 error

Tomcat has a JSR-356 (i.e. the websocket API) implementation since version 7.0.47. It provides also the javax.websocket-api-1.0.jar library so this is not needed in you application. You might need it at compile time but the server will provide it at runtime (that's what provided scope means in maven if you are not familiar with the tool)

Make sure javax.websocket-api-1.0.jar does not get deployed in your WAR, do a right click in your Eclipse server view, Clean... followed by Clean Tomcat work directory... then a Publish and try again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...