spring boot webscoket 简单实现

1. 引入pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.服务端代码

/**
 * 1.webscoket实现
 */
@ServerEndpoint(value = "/websocket/{group}/{param2}")
@Component
public class WebSocketTemplate {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    // 在线连接数
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    // 但springboot还是会为每个websocket连接初始化一个bean
    private static final CopyOnWriteArraySet<WebSocketTemplate> webSocketSet = new CopyOnWriteArraySet<WebSocketTemplate>();

    private static final Map<String, List<WebSocketTemplate>> webScoketMap = new HashMap<>();

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

    public static Map<String,List<WebSocketTemplate>> getWebSocketSet(){
        return webScoketMap;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen( @PathParam("group")String group,@PathParam("param2") String param2,Session session) {
        logger.info("group:" + group);// webscoket 自定义参数
        logger.info("param2:" + param2);// webscoket 自定义参数
        this.session = session;
        webSocketSet.add(this); // 加入集合中
        addOnlineCount();     // 在线人数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        if(WebSocketTemplate.onlineCount > 0){
            subOnlineCount();           //在线数减1
        }
        System.out.println("链接关闭,当前在线人数为" + getOnlineCount());
    }

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

    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    /**
     * 消息发送
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendAllMessage(String message) throws IOException {
        for (WebSocketTemplate item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

/**
 * 2.webscoket配置项
 */
@Configuration
public class WebSocketConfig {
    /**
     * websocket初始化bena
     * 使用@ServerEndpoint创立websocket endpoint
     * 首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    @Nullable
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
        threadPoolScheduler.setThreadNamePrefix("SockJS-");
        threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        threadPoolScheduler.setRemoveOnCancelPolicy(true);
        return threadPoolScheduler;
    }
}

/**
 *  3.webscoket测试
 */
@Controller
@RequestMapping("webScoket")
public class WebScoketController {
    @RequestMapping("gotoWbscoketTest")
    public String gotoWbscoketTest(){
        return "wbscoketTest";
    }

    @RequestMapping("size")
    @ResponseBody
    public ResultModel getSize(){
        int onlineCount = WebSocketTemplate.getOnlineCount();
        return  new ResultModel(ErrorMsg.SELECT_SUCCESS,onlineCount);
    }

    @RequestMapping("send")
    @ResponseBody
    public String sendMag(String msg){
        try {
            WebSocketTemplate.sendAllMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success";
    }

}

3.页面代码

<!DOCTYPE HTML>
<html>
<head>
    <title>WebSocket测试</title>
</head>

<body>
<h1>WebSocket测试</h1>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8090/websocket/param1/param2");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    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>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值