Websocket搭建(Vue+Springboot)

一、前言

springboot+vue快速搭建websocket简易模板。

二、后端

1、引入依赖

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

2.编写配置类

@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
        return new ServerEndpointExporter();
    }
}

3.消息处理

  • onopen:用于指定连接成功后执行
  • onmessage:用于从服务器接收到信息时执行。
  • onerror:用于指定连接失败后执行。
  • onclose:用于指定连接关闭后执行。
@Component
@Slf4j
@ServerEndpoint("/websocket/message/{uid}")
public class WebSocketServer {
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();

    /**
     * 连接uid
     */
    private String uid;

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

    /**
     * 连接建立成功调用的方法。
     */
    @OnOpen
    public void onOpen(@PathParam("sid") String uid, Session session) {
        onlineSessionClientMap.put(uid, session);
    }

    /**
     * 连接关闭方法
     */
    @OnClose
    public void onClose(@PathParam("uid") String uid, Session session) {
        onlineSessionClientMap.remove(uid);
    }

    /**
     * 收到客户端消息后调用的方法。
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        onlineSessionClientMap.forEach((onlineSid, toSession)->{
            toSession.getAsyncRemote().sendText(message);
        });
    }

    /**
     * 发生错误调用的方法
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 群发消息
     */
    private void sendToAll(String message) {
        onlineSessionClientMap.forEach((onlineSid, toSession) -> {
            if (!uid.equalsIgnoreCase(onlineSid)) {
                toSession.getAsyncRemote().sendText(message);
            }
        });
    }

    /**
     * 指定发送消息
     */
    private void sendToOne(String toSid, String message) {
        Session toSession = onlineSessionClientMap.get(toSid);
        if (toSession == null) {
            return;
        }
        toSession.getAsyncRemote().sendText(message);
    }
}

三、前端

连接websocket,并加入心跳

let heartbeatTimer = null

const user = useUserStore()
const websocketState = reactive({
    socket: null,
    url: 'ws://127.0.0.1:8081/websocket/message/'+user.userId,
    message: 'Hello, WebSocket!',
});

function connect () {
    websocketState.socket = new WebSocket(websocketState.url);
    websocketState.socket.onopen = () => {
        console.log('WebSocket已连接');
        startHeartbeat();
    };
    websocketState.socket.onclose = () => {
        console.log('WebSocket已断开');
        stopHeartbeat();
    };
    websocketState.socket.onmessage = (event) => {
        console.log(`收到消息:${event.data}`);
        if(event.data!='连接成功')
            open2(event.data)
    };
}

connect()

function startHeartbeat () {
  // 每隔一定时间发送心跳消息
  heartbeatTimer = setInterval(() => {
    if (websocketState.socket.readyState === WebSocket.OPEN) {
      websocketState.socket.send('Heartbeat')
    } else {
      console.log('WebSocket连接未打开')
      connect()
    }
  }, 60000)
}

function stopHeartbeat () {
  // 停止心跳定时器
  clearInterval(heartbeatTimer)
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

localhost:9000

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

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

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

打赏作者

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

抵扣说明:

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

余额充值