SpringBoot WebSocket配合react 使用消息通信

引入websocket依赖

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

配置websocket


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

@Configuration
@EnableWebSocket
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpoint() {
        return new ServerEndpointExporter();
    } 

}

websocket核心代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

@Component
@ServerEndpoint("/socket")
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
    private ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap(8);


    /**
     * 连接成功
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        String queryString = session.getQueryString();
        LOGGER.info("session id is {}", session.getId());
        LOGGER.info("queryString is {}", queryString);
        LOGGER.info("setup connection success userId is {}", session.getId());
        try {
            sendMessage(session, "cxk");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public void onMsg(String text, Session session) throws IOException {
        LOGGER.info("get message {}", text);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        LOGGER.error("get error");
    }

}

react 前端部分代码

import React, {useEffect, useState} from 'react';
    //	这里不要使用 import 或者 require 引入,否则报错

    useEffect(() => {
        const webSocket: WebSocket = new WebSocket('ws://localhost:8777/socket')
        webSocket.onopen = () => {
            console.log('ws onopen');
            webSocket.send('from client: hello');
        };
        webSocket.onmessage = (e) => {
            console.log('ws onmessage');
            console.log('from server: ' + e.data);
        };
    }, [])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值