springboot简单整合websocket
<!-- websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
/** * WebSocket方法 * @author Administrator * */ @Component @ServerEndpoint("/webSocket") public class WebSocket { private Session session; private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>(); /** * 开启 * @param session */ @OnOpen public void opOpen(Session session) { this.session = session; webSocketSet.add(this); System.out.println("有新的连接,总数:"+webSocketSet.size()); } /** * 关闭 */ @OnClose public void onClose() { webSocketSet.remove(this); System.out.println("连接断开,总数:"+webSocketSet.size()); } /** * 接受消息 * @param message */ @OnMessage public void onMessage(String message) { System.out.println("收到客户端消息:"+message); } /** * 发送消息 * @param message */ public void sendMessage(String message) { for (WebSocket webSocket : webSocketSet) { try { webSocket.session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } } } }
/** * 注入WebSocket * @author Administrator * */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
if('WebSocket' in window){ websocket = new WebSocket("ws://127.0.0.1:8080/......"); }else{ alert("该浏览器暂不支持websocket"); } websocket.onopen = function(event){ console.log("建立连接"); } websocket.onclose = function(event){ console.log("断开连接"); } websocket.onmessage = function(event){
String message = event.data //接受到消息后的逻辑 } websocket.onerror = function(event){ alert("websocket通讯发生错误"); } window.onbeforeunload = function(){ websocket.close(); }