java使用webSocket与前端通讯
maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
WebSocket服务
import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j //映射webSocket服务路径 @ServerEndpoint("/webSocket/{userId}") @Component public class MyWebSocket { private String userId; private Session session; private static Map<String,MyWebSocket> client = new ConcurrentHashMap<>(); @OnOpen public void onOpen(@PathParam("userId") String userId,Session session){ log.info("新连接:{}",userId); if (!isEmpty(userId)){ this.userId = userId; this.session = session; client.put(userId, this); log.info("现在连接的客户编码为:" + userId); } } /** * 关闭时执行 */ @OnClose public void onClose() { log.info("连接:{} 关闭", this.userId); } /** * 收到消息时执行 * @param message * @param session */ @OnMessage public void onMessage(String message, Session session) { log.info("收到用户{}的消息:{}", this.userId, message); //回复用户 session.getAsyncRemote().sendText("收到 " + this.userId + " 的消息:" + message); } /** * 连接错误时执行 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.info("用户id为:{}的连接发送错误", this.userId); error.printStackTrace(); } /** * 消息点对点推送 * @param message */ public void sendMessageToUser(String userId,String message) { MyWebSocket session = client.get(userId); if (session != null) { if (session.session.isOpen()) { session.session.getAsyncRemote().sendText("收到 " + userId + " 的消息:" + message); } else { log.info("用户session关闭"); } } else { log.info("用户session不存在"); } } private static boolean isEmpty(String s) { return s == null || s.length() == 0 || "".equals(s) || "null".equalsIgnoreCase(s) || "undefined".equalsIgnoreCase(s); } }
webSocketConfig
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { /** * 启用Springboot对WebSocket的支持 * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
前端websocket(index.html)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> websocket Demo---- user000 <br /> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"></div> <script type="text/javascript"> //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ //ws://localhost:8080/webSocket/100,当前userId为100 websocket = new WebSocket("ws://localhost:8080/webSocket/100"); console.log("link success") }else{ alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ setMessageInnerHTML("open"); } console.log("-----") //接收到消息的回调方法 websocket.onmessage = function(event){ setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function(){ setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); } </script> </body> </html>
启动项目:访问
@GetMapping("/socket") public void socket(String userId,String message){ myWebSocket.sendMessageToUser(userId,message); }