记录最近两天在本地搭建简单的springboot + websocket遇到的问题。
本地搭建正常运行,可以连接websocket,但是部署服务器后,会报错,无法连接。
Error during WebSocket handshake: Unexpected response code: 400 还是502错误来着。经过测试,发现在连接上出错
wss:连接 报错。最后在nginx配置上发现错误。正确配置如下:
#websocket
location /websocket {
proxy_pass http://127.0.0.1:2001;
proxy_http_version 1.1; #websoket必须要使用的协议,http 1.1
proxy_set_header Upgrade $http_upgrade; #要使用websocket协议时,响应http升级请求
proxy_set_header Connection "upgrade";
}
这时候可以正常联通websocket。
另外,如果使用的是独立的Tomcat,那么要将如下Bean注释掉,该bean会使用springboot内部的tomcat
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
出错问题,可以从下面几点排查:
1、防火墙是否有禁用相应端口。
2、在配置好springboot+websocket后,不着急写网页去wss连接,可以百度搜索websocket在线测试工具,测试是否项目搭建成功,这样可以在最开始配置阶段知道是否成功,排查起来省力。
3、重点查看nginx的配置是否正确。在配置完成后记得要重启Nginx。
如果还存在问题,可以评论一起沟通学习。 |