我正在尝试使用Java Websocket API(1.0)-JSR 356中指定的带注释的终结点在tomcat 7.0.50上实现websocket。下面是我编写代码的简要步骤1)使用@ServerEndpoint注释编写一个websocket终结点2)实现@onOpen和@onMessage方法3)在google chrome上使用javascript打开websocket。
请按顺序查找与上述步骤对应的代码
1)步骤1和2-编写Websocket服务器端点:
package com.jkweb.websocket; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ServerEndpoint(value="/websocket/fileuploadtracker") @OnOpen public void open(Session session,EndpointConfig config) { ...... } @OnMessage public void onMessage(Session session, String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { logger.error(e.getMessage()); } } public static void sendMessage(String uniqueTocken,String msg){ try { Session wsSession = socketConnectionMap.get(uniqueTocken); wsSession.getBasicRemote().sendText(msg); } catch (IOException e) { logger.error(e.getMessage()); } }
}
2)第3步-使用Chrome中的javascript API打开websocket:
wsurl = "ws://localhost:8080/jkweb/websocket/fileuploadtracker", ws; ws = new WebSocket(wsurl); ws.onopen = function() { // Web Socket is connected, send data using send() ws.send("Sending first Message"); alert("Message is sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Message is received..."); }; ws.onclose = function(evt) { // websocket is closed. alert("Connection is closed..."+evt.code + ":"+evt.reason ); };
我正在使用以下版本的软件:1)Tomcat-7.0.50 2)Java-1.7.45 3)Servlet-3.0 4)包含以下Maven依赖项5)Chrome-32.0.1700.107m
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version> <scope>provided</scope> </dependency>
但是我收到以下错误,Chrome控制台中的连接被1066错误代码关闭:
WebSocket connection to 'ws://localhost:8080/jkweb/websocket/fileuploadtracker' failed: Error during WebSocket handshake: Unexpected response code: 404
有没有我遗漏的配置。我尝试搜索很多,但是找不到任何东西。请我尽快解决此问题。
我已经解决了 问题是我的安装所特有的。我的应用程序的WEB-INF / lib目录中也安装了websocket api .jar。不知道为什么会破坏它。您能否阐明这种现象的根本原因,以及为什么在将应用程序的WEB-INF / lib中的websocket- api.jar与tomcat的lib一起提供给websocket-api.jar时,它为什么不起作用?