websocket集成文档

1.添加依赖

xml 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.添加配置

java 复制代码
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.添加websocket处理器

java 复制代码
@Setter@Getter
@ServerEndpoint("/{token}")
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<>();
    /**
     * 浏览器和服务器在建立连接
     * @param session
     * @param token
     */
    @OnOpen
    public void onOpen(Session session, @PathParam( "token") String token){
        System.out.println("客户端连接===>"+token);
        clients.put(token,session);
    }
    /**
     * 客户端发送消息
     * @param message
     * @param token
     */
    @OnMessage
    public void onMessage(String message, @PathParam( "token") String token){
        System.out.println("客户端:"+token+",发送消息:"+message);
        //发送消息
        clients.get(token).getAsyncRemote().sendText(message);
    }
    /**
     * 浏览器和服务器之间断开连接之后会调用此方法.
     * @param token
     */
    @OnClose
    public void onClose(@PathParam( "token") String token){
        System.out.println("客户端:"+token+",断开连接");
        //删除关系
        clients.remove(token);
    }
    /**
     * 通讯异常触发该事件
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}

4.提供接口获取浏览器发送的消息

java 复制代码
@RestController
public class MsgContoller {
    @RequestMapping("/sendMsg")
    public String sendMsg(String token,String msg) throws IOException {
        Session session = OrderWebSocketServer.clients.get(token);
        session.getBasicRemote().sendText(msg);
        return "发送成功";
    }
}
相关推荐
EasyDSS3 小时前
超越“接收端”:解析视频推拉流EasyDSS在RTMP推流生态中的核心价值与中流砥柱作用
网络·音视频
小糖学代码4 小时前
网络:2.Socket编程UDP
网络·网络协议·udp
Empty_7774 小时前
Python编程之常用模块
开发语言·网络·python
m0_611779964 小时前
MQTT和WebSocket的差别
网络·websocket·网络协议
AORO20255 小时前
防爆手机与普通手机有什么区别?防爆手机哪个牌子好?
运维·服务器·网络·5g·智能手机·信息与通信
paopaokaka_luck5 小时前
基于SpringBoot+Vue的数码交流管理系统(AI问答、协同过滤算法、websocket实时聊天、Echarts图形化分析)
vue.js·人工智能·spring boot·websocket·echarts
望获linux5 小时前
【实时Linux实战系列】使用 u-trace 或 a-trace 进行用户态应用剖析
java·linux·前端·网络·数据库·elasticsearch·操作系统
对岸住着星星5 小时前
断电重启后自动重连WiFi并分配固定IP的Armbian脚本
服务器·网络·tcp/ip
red watchma5 小时前
Xshell->MCU Ymodem协议实现
网络·单片机·嵌入式硬件
sky北城5 小时前
读书笔记整理--网络学习与概念整合
网络·智能路由器