消息推送springboot+websocket简单demo

这里为了方便,使用springboot实现。模板引擎使用thymeleaf(默认)。

springboot+websocket demo下载:https://gitee.com/chen_jia_hao/websocket

1、Intellj Idea 创建新的springboot项目。

可参考下面部分截图:

整个demo结构如下所示:

2、配置类,需配置如下,方可使用websocket。

package com.cjh.websocket.config;

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

/**
 * @author chen jia hao
 */
@Configuration
public class WebConfig {
    /**
     * 支持websocket
     * 如果不使用内置tomcat,则无需配置
     * @return
     */
    @Bean
    public ServerEndpointExporter createServerEndExporter(){
        return new ServerEndpointExporter();
    }
}

3、websocket服务端处理类(核心)

package com.cjh.websocket.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket服务端
 * @author chen jia hao
 */
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocket {

    //用来存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<MyWebSocket> user = new CopyOnWriteArraySet<MyWebSocket>();

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

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {

        //群发消息
        for (MyWebSocket myWebSocket : user) {
            myWebSocket.session.getBasicRemote().sendText(session.getId()+"说:"+message);
            //myWebSocket.session.getBasicRemote().sendText("<img src=''/>");
        }
    }

    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId()+" open...");
        this.session = session;
        user.add(this);
    }
    @OnClose
    public void onClose(){
        System.out.println(this.session.getId()+" close...");
        user.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this.session.getId()+" error...");
        error.printStackTrace();
    }

}

4、前台界面,聊天测试

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        #message{
            height: 520px;
            border-bottom: 1px solid gray;
            padding: 20px 30px;
        }
        #container{
            margin: 0 auto;
            width: 720px;
            border: 1px solid gray
        }
        input{
            width: 300px;
            height: 36px;
            border: 1px solid gray;
            background:none;
            outline:none;
        }
        input:focus{
            border-color: yellow;
        }
        button{
            height: 36px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="message">

    </div>
    <div>
        <input id="text" type="text" placeholder="输入内容..."/>
        <button onclick="send()">发送消息</button>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/myWebSocket");
    }
    else {
        alert('当前浏览器不支持websocket');
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var data = event.data;
        document.getElementById('message').innerHTML += data+'<br/>';
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("onopen...");
    }
    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("onclose...");
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("onerror...");
    };
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

</script>
</body>
</html>

6、demo效果图:

 

  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值