WebSocket 404 错误 [英] WebSocket 404 error
问题描述
我正在尝试在我的网站上实施 WebSocket.按照基本教程,我添加了这个类:
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); }
}
还有这个 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...");
};
我将 js 添加到我的一个页面中,并且只调用了 ws.onclose
,在控制台中我收到此错误:
I added the js to one of my pages, and only ws.onclose
is called, in console I get this error:
Firefox
:Firefox 无法与服务器建立连接ws://localhost:8080/Mysite/websocketendpoint
Firefox
: Firefox can't establish a connection to the server at ws://localhost:8080/Mysite/websocketendpoint
Chrome
:WebSocket 握手期间出错:意外的响应代码:404
Chrome
: Error during WebSocket handshake: Unexpected response code:
404
我尝试使用 'ws://echo.websocket.org' 作为 wsUri
并且它有效,所以我猜问题出在服务器端.
I tried using 'ws://echo.websocket.org' as wsUri
and it works, so I guess the problem is on server side.
我正在使用以下库:javaee-api-7.0、javax.websocket-api-1.0我的浏览器与 websockets 兼容(我检查过)
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
推荐答案
您可能想要检查这是否是您错误的根源:tomcat 7.0.50 java webscoket 实现给出404错误
You might want to check if this is the root of your error: tomcat 7.0.50 java webscoket implementation gives 404 error
Tomcat 从 7.0.47 版本开始就有 JSR-356(即 websocket API)实现.它还提供了 javax.websocket-api-1.0.jar
库,因此您的应用程序中不需要它.您可能在编译时需要它,但服务器会在运行时提供它(如果您不熟悉该工具,这就是 provided
范围在 maven 中的含义)
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)
确保 javax.websocket-api-1.0.jar
没有部署在你的 WAR 中,在你的 Eclipse 服务器视图中右键单击,Clean...
然后是 Clean Tomcat work directory...
然后是 Publish
并重试.
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.
这篇关于WebSocket 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!