编者按
postman 8.5 以上支持 websocket。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
问题描述
由于是 第一次用 postman连接 websocket 测试,摔得鼻青脸肿。 在此记录一下。
用 postman 连接 websocket 后,一直返回 200,如下图。
解决方法
在 websocket配置的 代码中 去掉 withSockJS(); 有这句 postman 就无法 连接 websocket,再用 sockJS连接时候 在加上即可。
去掉之后 postman 即可成功 连接。
如果有 鉴权,记得 将 /ws/** 添加 白名单。
附上websocket 配置。
package com.peove.testdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* @author: Cgxin
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* 添加这个Endpoint,这样在网页就可以通过 websocket 连接上服务
* 也就是配置 websocket 的服务地址,并且可以指定是否使用 socketJS
*
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
/**
* 1.将 ws/ep 路径注册为 stomp 的端点,用户连接了这个端点就可以镜像 websocket 通讯,支持 socketJS
* 2.setAllowedOrigins("*"):允许跨域
* 3.withSockJS():支持socketJS访问
*/
System.err.println("websocket 连接端点: /ws/ep "); // TODO===delete
registry.addEndpoint("/ws/eq").setAllowedOrigins("*");
}
//配置消息代理
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 配置代理域,可以配置多个,配置代理目的地前缀为 /queue ,可以在配置域上像客户端推送消息
registry.enableSimpleBroker("/queue");
}
}
websocket 相关知识
Gateway整合websocket stomp (我没有用这个单独注册一个服务,依旧用的 匹配 路由,可以转发。)
Stomp、websoket播、点对点发消息demo