最近项目中用到了websocket,记录一下注意事项 1.tomcat版本(7.42不支持,7.57支持,检查tomcat lib中是否存在websocket-api.jar) 2.url设置 (ws://localhost:8080/a/websocket)
server端
package websocket; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/websocket") public class WebSocketTest { @OnMessage public void onMessage(String message, Session session) throws IOException, InterruptedException { // 1.接收的信息 System.out.println("收到: " + message); // 2.向客户端发信息 session.getBasicRemote().sendText("开始"); // 3.隔一段时间发一条信息 int sentMessages = 0; while(sentMessages < 3){ Thread.sleep(1000); session.getBasicRemote(). sendText("发送topic数据. 测试: " + sentMessages); sentMessages++; } // 4.结束发送 session.getBasicRemote().sendText("结束"); } @OnOpen public void onOpen () { System.out.println("连接客户端"); } @OnClose public void onClose () { System.out.println("断开连接"); } }
前台页面
<!DOCTYPE html> <html> <head> <title> websockets测试</title> </head> <body> <div> <input type="submit" value="开始" onclick="start()" /> </div> <div id="messages"></div> <script type="text/javascript"> //设置URL var webSocket = new WebSocket('ws://localhost:8080/a/websocket'); 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 = '连接已建立'; } function onError(event) { alert(event.data); alert("error"); } //向服务器发送信息 function start() { webSocket.send('订阅topic'); return false; } </script> </body> </html>
效果图
时间: 2024-10-05 04:00:55