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 "发送成功";
    }
}
相关推荐
云飞云共享云桌面16 分钟前
替代传统电脑的共享云服务器如何实现1拖8SolidWorks设计办公
linux·运维·服务器·网络·电脑·制造
RollingPin1 小时前
iOS八股文之 网络
网络·网络协议·ios·https·udp·tcp·ios面试
惘嘫、冋渞7 小时前
AWS同一账号下创建自定义VPC并配置不同区域的对等链接
网络·云计算·aws
云知谷8 小时前
【HTML】网络数据是如何渲染成HTML网页页面显示的
开发语言·网络·计算机网络·html
呉師傅13 小时前
关于联想ThinkCentre M950t-N000 M大师电脑恢复预装系统镜像遇到的一点问题
运维·网络·windows·电脑
代码AI弗森13 小时前
无状态的智慧:从 HTTP 到大模型的系统进化论
网络·网络协议·http
酷熊代理13 小时前
安卓手机 IP 切换指南:告别卡顿,轻松换 IP
网络·网络协议·tcp/ip·socks5
不做菜鸟的网工14 小时前
PIM SM +MSDP 组播跨域配置案例
网络协议
月上柳青14 小时前
快速创建无线AP热点
网络·智能路由器
K_i13415 小时前
云原生网络基础:IP、端口与网关实战
网络·ip·接口隔离原则