<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
webSocket的配置类
package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; import org.springframework.web.socket.config.annotation.EnableWebSocket; /** * @ClassName: WebSocketConfig * @Auther: zhaoxiuhao * @Date: 2020/12/5 17:33 * @Description: TODO * @Version: 1.0 */ @Configuration @EnableWebSocket public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpoint() { return new ServerEndpointExporter(); } }
websocket的连接监听
package com.example.websocket; import com.alibaba.fastjson.JSONObject; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.ServerEndpointExporter; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * */ @ServerEndpoint("/webSocket/{username}") @Component public class WebSocket { private static int onlineCount = 0; private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); private Session session; private String username; public WebSocket() { System.out.println(1111); } /** * 建立连接的时候 **/ @OnOpen public void onOpen(@PathParam("username") String username, Session session) throws IOException { this.username = username; this.session = session; addOnlineCount(); clients.put(username, this); System.out.println("已连接"); } @OnClose public void onClose() throws IOException { clients.remove(username); subOnlineCount(); } @OnMessage public void onMessage(String message) throws IOException { JSONObject jsonObject = JSONObject.parseObject(message); String mes= jsonObject.getString("message"); if (!jsonObject.getString("To").equals("All")) { sendMessageTo(mes, jsonObject.getString("To")); } else { sendMessageAll("给所有人"); } } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } //给某个人发送信息 public void sendMessageTo(String message, String To) throws IOException { for (WebSocket item : clients.values()) { if (item.username.equals(To) ) item.session.getAsyncRemote().sendText(message); } } //给所有人发送信息 public void sendMessageAll(String message) throws IOException { for (WebSocket item : clients.values()) { item.session.getAsyncRemote().sendText(message); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocket.onlineCount++; } public static synchronized void subOnlineCount() { WebSocket.onlineCount--; } public static synchronized Map<String, WebSocket> getClients() { return clients; } public Session getSession() { return session; } }
主动调用后台的方法推送信息
package com.example.websocket; import com.example.websocket.WebSocket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.Map; /** * @ClassName: WebSocketController * @Auther: zhaoxiuhao * @Date: 2020/12/5 16:20 * @Description: TODO * @Version: 1.0 */ @RestController @RequestMapping("/socket") public class WebSocketController { @Autowired private WebSocket webSocket; @RequestMapping("/sendMessage") public void sendMessage(@RequestParam("message")String message) throws IOException { webSocket.sendMessageAll(message); } }
前端建立websocket连接
mounted() { var host = document.location.host; const url = 'ws://192.168.0.102:8081/' + 'webSocket/' + "user"; var websocket = null // alert(url) if ('WebSocket' in window) { websocket = new WebSocket(url); //alert("支持WebSocket协议"); } else { alert("不支持WebSocket协议"); } //WebSocket连接发生错误的回调方法 websocket.onerror = function () { console.log("连接失败") }; //WebSocket连接成功建立的回调方法 websocket.onopen = function () { console.log("WebSocket连接成功"); }; //接收到消息的回调方法 websocket.onmessage = (event)=> { console.log("接收到推送过来的信息",event.data) this.$notify({ showClose: true, message: '单击'+JSON.stringify(event.data), type: 'success', }); // websocket.close(); // alert("webSocket已关闭!") }; //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { //closeWebSocket(); }; //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //连接关闭的回调方法 websocket.onclose = function () { console.log("WebSocket连接关闭"); };