java代码如下
import java.util.concurrent.TimeUnit; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/cmd/prog") public class Progress { @OnMessage public void onMessage(String msg, Session session) throws Exception { System.out.println("-------onMessage-------"); System.out.println("msg : " + msg); System.out.println(session.getQueryString()); for(int i=0;i<=100;i++) { String tmp = "让我们定义一个 Java EE websocket服务器端" + i; System.out.println("send msg : " + tmp); session.getBasicRemote().sendText(tmp); TimeUnit.SECONDS.sleep(1l); } } @OnOpen public void onOpen() { System.out.println("------------onOpen------------"); } @OnClose public void onClose() { System.out.println("------------onClose------------"); } }
maven配置的依赖是:
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency>
<button onclick="start()">测试</button> <div id="messages"></div> <script type="text/javascript"> var webSocket = null; function init() { webSocket = new WebSocket('ws://127.0.0.1:8080/cmd/prog'); webSocket.onerror = function(event) { onError(event) }; webSocket.onopen = function(event) { onOpen(event) }; webSocket.onmessage = function(event) { onMessage(event) }; } function onMessage(event) { document.getElementById('messages').innerHTML += '<br />' + event.data; } function onOpen(event) { document.getElementById('messages').innerHTML = 'Connection established'; } function onError(event) { alert(event.data); } function start() { init(); } </script>
http://127.0.0.1:8080/index.jsp
点击按钮,报错:
WebSocket connection to 'ws://127.0.0.1:8080/cmd/prog' failed: Error during WebSocket handshake: Unexpected response code: 404
系统运行环境为:
jdk1.8 x64, tomcat7.0.57
网上貌似是说,要引入tomcat-socket的jar,但是这样做,肯定只能在tomcat下运行,不能在其他web server下运行
请问,怎么解决。
引用来自“逝水fox”的评论
ServerEndpoint这些注解是JavaEE7的内容,记得Tomcat得要8.0才能支持。Tomcat7的话,WebSocket是靠Servlet继承WebSocketServlet 来实现的引用来自“逝水fox”的评论
ServerEndpoint这些注解是JavaEE7的内容,记得Tomcat得要8.0才能支持。Tomcat7的话,WebSocket是靠Servlet继承WebSocketServlet 来实现的大神,为何在Tomcat 7的示例中,可以运行ServerEndpoint注解的WebSocket???
真的想知道,我也被这个问题困扰一天了
这个项目还做了其他xml配置吗,controller还用不用写其他方法