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 "发送成功";
    }
}
相关推荐
2401_8734794043 分钟前
应急响应:勒索软件攻击源IP分析,如何通过IP地址查询定位辅助溯源?
网络·tcp/ip·安全·网络安全·ip
nibabaoo2 小时前
前端开发攻略---H5页面手机获取摄像头权限回显出画面并且同步到PC页面
javascript·websocket·实时音视频·实时同步·录制
拾薪2 小时前
[SuperPower] Brainingstorm - 流程控制架构分析
网络·人工智能·ai·架构·superpower·brainstorming
IMPYLH2 小时前
Linux 的 rm 命令
linux·运维·服务器·网络·bash
white-persist3 小时前
【vulhub shiro 漏洞复现】vulhub shiro CVE-2016-4437 Shiro反序列化漏洞复现详细分析解释
运维·服务器·网络·python·算法·安全·web安全
黄俊懿3 小时前
【架构师从入门到进阶】第五章:DNS&CDN&网关优化思路——第一节:DNS优化
网络·计算机网络·架构·系统架构·cdn·dns·架构设计
Byron Loong4 小时前
【网络】Python 怎么做TCP通讯
网络·python·tcp/ip
裕工实验室5 小时前
功率模块为什么一定要用陶瓷PCB?从结构到选材一篇讲清(附DPC / DBC / AMB选型逻辑)
网络·硬件工程·pcb工艺·材料工程
SilentSamsara5 小时前
HTTP/1.1 到 HTTP/3:每代协议解决了什么问题
网络·网络协议·tcp/ip·http·https
Flash.kkl6 小时前
传输层UDP、TCP
网络协议·tcp/ip·udp