侧边栏壁纸
博主头像
杨不易呀

你的压力来源于无法自律,只是假装努力,现状跟不上内心欲望,所以你焦虑又恐慌。——杨不易呀

  • 累计撰写 72 篇文章
  • 累计创建 73 个标签
  • 累计收到 23 条评论

从零玩转Websocket实时通讯服务之前后端分离版本

杨不易呀
2021-10-25 / 0 评论 / 0 点赞 / 1,143 阅读 / 946 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-08-22,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

前言

公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.

后端搭建

一、依赖导入

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

二、搭建websocket服务

1.WebSocketConfig配置文件
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yby6.com.
 =============================================================================*/

package top.yangbuyi.service_websocket.config;

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


/**
 * 配置文件
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
@Configuration
public class WebSocketConfig {


	/**
	 * 给Spring容器注入 ServerEndpointExporter 对象
	 *
	 * @return {@link ServerEndpointExporter}
	 */
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}
}
2.WebSocketServer服务
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yby6.com.
 =============================================================================*/

package top.yangbuyi.service_websocket.server;

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.Date;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket前端请求服务地址
 *
 * /service_websocket/wspoint/yangbuyi
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
@ServerEndpoint("/service_websocket/wspoint/{loginName}")
@Component
public class WebSocketServer {

    /**
     * 存储每一个连接
     */
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 登录名
     */
    private String loginName = "";


    /**
     * 在开放
     *
     * @param session   会话
     * @param loginName 登录名
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("loginName") String loginName) {
        // 前端连接得到登陆名称
        this.loginName = loginName;
        // 当前websokcet生成的会话
        this.session = session;
        webSocketSet.add(this);
        try {
            sendMessage("success");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 在关闭
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }


    /**
     * 在消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到来自[" + message + "]发送的消息" + session);
        // 发送消息
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message + ",时间:" + new Date() + session);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * 在错误
     *
     * @param session 会话
     * @param error   错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            if (this.session != null) {
                this.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息
     * 发送指定消息给某个用户
     *
     * @param userName 用户名
     * @param msgStr   消息信息
     */
    public static void sendInfo(String userName, String msgStr) {
        for (WebSocketServer item : webSocketSet) {
            if (item.loginName.equals(userName)) {
                item.sendMessage(msgStr);
            }
        }
    }
}

自己写个controller

进行调用测试服务端消息发送

    /***
     * userName 用户唯一标识 看你业务来 用户名称  用户id 都可以
     */
    @GetMapping("/sendMessage")
    public String sendMessage(String userName) {
 	// 发送消息提示到前端
 	WebSocketServer.sendInfo("这里是服务端发送的消息", userName);
        return "yes";
    }



前端搭建

一、index.vue

<!--============================================================================
  = - Yang Buyi  Copyright (c) 2021 https://yby6.com.
  ===========================================================================-->

<template>
  <div class="webSocket">
    <button id="send" class="btn btn-default" @click="sendMsg('发送杨不易https://yby6.com')">Send</button>
    <div v-for="item in msgData" :key="item">
      {{ item }}
    </div>
  </div>
</template>
<script>

export default {
  name: 'WebSocket',
  data() {
    return {
      // 消息
      msgData: [],
      websocket: null
    }
  },
  mounted() {
    this.connection()
    // this.initWebSocket()
  },
  destroyed() {
    if (this.websocket != null) this.websocket.close() // 离开路由之后断开websocket连接
  },
  methods: {
    initWebSocket() {
      this.connection()
      // const that = this
      // // 断开重连机制,尝试发送消息,捕获异常发生时重连
      // this.timer = setInterval(() => {
      //   try {
      //     that.websocket.send('hello')
      //   } catch (err) {
      //     console.log('断线了: ' + err)
      //     that.connection()
      //   }
      // }, 5000)
    },

    /**
     * 连接后台ws
     */
    connection() {
      const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称'
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
        this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!')
      } else {
        this.websocket = new WebSocket(socketUrl)
        console.log(this.websocket)
        this.websocket.onopen = this.websocketOnopen // 连接成功
        this.websocket.onmessage = this.websocketOnmessage // 广播成功
        this.websocket.onerror = this.websocketOnerror // 连接断开,失败
        this.websocket.onclose = this.websocketClose // 连接关闭
      }
    },
    websocketOnopen() {
      this.sendMsg('连接成功第一次https://yby6.com')
      console.log('连接成功')
    },
    websocketOnerror() {
      console.log('连接失败')
    },
    websocketClose() {
      console.log('断开连接')
    },
    websocketOnmessage(data) {
       // 接收 服务端来的数据
      this.msgData.push(data)
    },
    sendMsg(val) {
      this.websocket.send(val)
    }
  }
}
</script>

测试调用创建的controller 向前端发送消息

0
广告 广告

评论区