SpringBoot使用Socket向前端推送消息

个人资源与分享网站:http://xiaocaoshare.com/

1.对webSocket理解
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
2.使用webSocket好处
HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
3.SpringBoot2.0,在pom.xml加入以下依赖
<dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  
 </dependency> 
4.开启webSocket支持
在SpringBoot配置类配置Bean
@Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
5.WebSocketServer
@ServerEndpoint("/websocket")
@Component
@Slf4j
public class WebSocketServer {

    // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    // 接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this); // 加入set中
        addOnlineCount(); // 在线数加1
        log.info("有新连接加入!当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); // 从set中删除
        subOnlineCount(); // 在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
        // 群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {

        for (WebSocketServer item : webSocketSet) {
            try {
                // 这里可以设定只推送给这个sid的,为null则全部推送

                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}

6.消息推送
写个控制器,调用WebSocketServer.sendInfo();
@RestController
public class SendMessageController {

    @RequestMapping("sendInfo")
    public String sendInfo(@RequestParam String msg) {
        try {
            WebSocketServer.sendInfo(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return "信息发送异常!";
        }
        return "发送成功~";
    }
}

7.页面代码
<!DOCTYPE HTML>
  <html>
  <head>
      <title>WebSocket</title>
  </head>
  
  <body>
  <div style="width: 800px;height: 100%; margin: 0px auto;">
      <span style="color: coral; font-size: 22px;"> Welcome WebSocket</span><br/><br/>
     <div id="message">
     </div>
 </div>
 </body>
 
 <script type="text/javascript">
     var websocket = null;
     //判断当前浏览器是否支持WebSocket
     if('WebSocket' in window){
         websocket = new WebSocket("ws://localhost:8002/websocket");
     }else{
         alert('连接失败!!')
     }
 
     //连接发生错误的回调方法
     websocket.onerror = function(){
         setMessageInnerHTML("error");
     };
 
     //连接成功建立的回调方法
     websocket.onopen = function(event){
         setMessageInnerHTML("webSocket 连接成功~");
     }
 
     //接收到消息的回调方法
     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();
     }
 
   </script>
 </html>

8.测试
1.建立2个连接,就是打开两个窗口,访问http://localhost:8002/websocket.html

2.后台向前端推送消息
新打开一个窗口,访问http://localhost:8002/sendInfo?msg=测试websocket

代码:https://github.com/xiaoyirang/SpringBootDemo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章