spring boot 集成WebScoket(端口推送)

spring boot 集成WebScoket(特定端口推送)

  • 1.什么是WebScoket
  • 2.代码示例

参考文章地址:
WebScoket原理: https://www.cnblogs.com/fuqiang88/p/5956363.html
端口消息推送: https://blog.csdn.net/moshowgame/article/details/80275084
Netty的高性能Websocket服务器: https://blog.csdn.net/moshowgame/article/details/83663018

1.什么是WebScoket

spring boot 集成WebScoket(端口推送)_第1张图片
spring boot 集成WebScoket(端口推送)_第2张图片
Http协议的缺陷:通信只能由客户端发起,服务器无法主动向客户端推送信息。使用ajax轮询、long poll浪费资源。

2.代码示例

maven依赖

 	<dependency>  
         <groupId>org.springframework.bootgroupId>  
         <artifactId>spring-boot-starter-websocketartifactId>  
   	dependency> 

	

WebSocketConfig

 	package com.myself.computerThinking.WebScoket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


/**
 * 开启WebScoket支持
 */
@Configuration
public class WebScoketConfig {

    /**
     * * 注入对象ServerEndpointExporter,
     *  * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
 

WebSocketServer
因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接@ServerEndpoint("/websocket")@Component启用即可,然后在里面实现@OnOpen,@onClose,@onMessage等方法

package com.myself.computerThinking.WebScoket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。
 * 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
 */
@ServerEndpoint("/websocket/{sid}")
@Component     //此注解千万千万不要忘记,它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebSocketServer {

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

    private static ConcurrentHashMap<String, ArrayList<WebSocketServer>> webSocketServers = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private String sid="";
    /**
     * 建立连接成功的方法
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        ArrayList<WebSocketServer> list=webSocketServers.get(sid);
        if(list==null){
            list = new ArrayList<>();
            webSocketServers.put(sid,list);
        }
        list.add(this);
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketServers.get(this.sid)!=null){
            webSocketServers.get(this.sid).remove(this);
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
        }

    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     *
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
            try {
                this.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    
    @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,@PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口"+sid+",推送内容:"+message);
        ArrayList<WebSocketServer> webSocketServerList =webSocketServers.get(sid);
        if(webSocketServerList!=null){
            for (WebSocketServer webSocketServer:webSocketServerList){
                webSocketServer.sendMessage(message);
            }
        }
    }

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

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

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

消息推送

package com.myself.computerThinking.WebScoket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/checkcenter")
public class WebSocketController {

    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav=new ModelAndView("/webScoket");
        mav.addObject("cid", cid);
        return mav;
    }
    //推送数据接口
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Object pushToWeb(@PathVariable String cid, String message) {
        LinkedHashMap result= new LinkedHashMap();
        try {
            WebSocketServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("error",cid+"#"+e.getMessage());
            result.put("code",500);
            return result;
        }
        result.put("success",cid);
        result.put("code",200);
        return result;
    }
}

页面发起socket请求


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>接受消息title>
head>
<body>

body>
<script th:inline="javascript">
    var socket;
    var cid=[[${cid}]]
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://localhost:8080/websocket/"+cid);
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时,关闭socket
        //jquery1.8中已经被废弃,3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
script>
html>

连接地址:
http://localhost:8083/checkcentersys/checkcenter/socket/20

你可能感兴趣的:(spring boot 集成WebScoket(端口推送))