springboot+vue 使用websocket后台主动向前台推送消息

14 篇文章 0 订阅

后台springboot代码

引入依赖

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

配置类

@Configuration
public class CommonConfig {

    /**
     * websocket配置
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

websocket服务类

@ServerEndpoint("/websocket/{username}")
@Slf4j
@Component
public class Websocket {
    //静态变量,用来记录当前在线连接数。设计为安全的
    private static int onlineCount = 0;
    //concurrentHashMap分段锁,用来存放每个客户端对应的Websocket对象。
    private static Map<String, Websocket> clients = new ConcurrentHashMap<String, Websocket>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private String username;

    /**
     * 连接建立成功调用的方法
     * @param username
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        this.username = username;
        this.session = session;
        Websocket.onlineCount++;
        log.info("有一连接进入!当前在线人数为" + onlineCount);
        clients.put(username, this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        clients.remove(username);
        Websocket.onlineCount--;
        log.info("有一连接关闭!当前在线人数为" + onlineCount);

    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到客户端的消息"+message);
        sendMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket发生错误:" + throwable.getMessage());
    }

    public static void sendMessage(String message) {
        // 向所有连接websocket的客户端发送消息
        // 可以修改为对某个客户端发消息
        for (Websocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }
}

测试请求方法

@RestController
@RequestMapping("/news")
public class NewsController {

    @GetMapping("/send")
    public String send(){
        Websocket.sendMessage("这是websocket群发消息!");
        return "发送消息成功";
    }

}

前端VUE

这是在创建vue项目自带的HelloWorld.vue文件里修改的

<template>
  <div class="hello">
    <h1>测试webSocket</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },

  created() { // 页面创建生命周期函数
    this.initWebSocket()
  },
  destroyed: function () { // 离开页面生命周期函数
    this.websocketclose();
  },
  methods: {
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
      this.websock = new WebSocket("ws://127.0.0.1:8031/websocket/test");
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen: function () {
      console.log("WebSocket连接成功");
    },
    websocketonerror: function () {
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage: function (e) {
      console.log(e.data);                // console.log(e);
    },
    websocketclose: function (e) {
      console.log("connection closed (" + e.code + ")");
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

测试

OK!代码部分已结束,现在先启动后台springboot,和前端vue。打开页面按下F12看日志打印。

非常好,这时候说明前后端websocket已经连接成功了。
下面用你的工具(http测试工具,postman之类的)测试推送消息接口。

很棒,调用接口成功,信息成功发送。下面看看前端是否收到。

OK!大功告成!各位朋友!
good luck!
后会有期!

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现基于Spring BootVueWebSocket的聊天室并持久化消息,您需要完成以下步骤: 1. 创建Spring Boot项目 使用Spring Initializr创建一个基于Maven或Gradle的Spring Boot项目。 2. 配置WebSocketSpring Boot项目中,您需要配置WebSocket。可以使用Spring的`@EnableWebSocket`注解来开启WebSocket。 3. 编写WebSocket处理程序 创建一个WebSocket处理程序来处理WebSocket连接和消息。这个处理程序应该继承`TextWebSocketHandler`类,并实现`handleTextMessage()`方法来处理WebSocket消息。在处理程序中,您可以将接收到的消息存储到数据库中,以便在断开连接后仍然可以访问它们。 4. 创建Vue项目 使用Vue CLI创建一个新的Vue项目。 5. 集成VueWebSocketVue项目中,使用`vue-socket.io`库来集成WebSocket。这个库提供了一个`socket`对象,您可以使用它来发送和接收WebSocket消息。在Vue组件中,您可以使用`socket`对象来连接WebSocket服务器,并处理接收到的消息。 6. 编写聊天室界面 在Vue项目中,创建一个聊天室界面。这个界面应该包括一个输入框和一个消息列表。当用户在输入框中输入消息时,使用`socket`对象将该消息发送到WebSocket服务器。当接收到新消息时,将它们添加到消息列表中。 7. 持久化消息Spring Boot项目中,您可以使用JPA和Hibernate等ORM框架来将消息存储到数据库中。当处理程序接收到新消息时,将它们保存到数据库中。当用户重新连接到聊天室时,您可以从数据库中检索以前的消息并将它们添加到消息列表中。 完成以上步骤后,您应该能够创建一个基于Spring BootVueWebSocket的聊天室,并持久化消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖行骗老中医

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值