springboot+websocket的简单实现,解决websocket failed: Error during WebSocket handshake: Unexpected response

本文详细介绍了如何在SpringBoot项目中实现WebSocket功能,包括项目结构搭建、前后端代码实现及ServerEndpointExporter的注入,实现即时通讯。

编辑器:idea。tomcat是springboot内置的tomcat,一开始出现

websocket failed: Error during WebSocket handshake: Unexpected response

这个问题的原因是,我一开始在项目中没有在注入ServerEndpointExporter ,后来注入后就能完整的运行了。

下面开始简单的实现过程:

我的项目结构:(该实现是客户端的实现,没有设置服务端的实现)

一、首先,创建springboot项目,在pox.xml中加入(下面是我的pom.xml的dependencies里的全部依赖,因为,这个是最简单的入门例子,所以只有主要的websocket和web依赖)

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--websocket连接需要使用到的包-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

二、创建一个页面index.html,前端跳转后端的一些必要代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:8080/websocket');
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

三、后端的socket处理

WebSockTest.java
/**
 * @ServerEndPoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL连接到websocket服务器端
 */
@ServerEndpoint("/websocket")
@Component
public class WebSockTest {
    private static int onlineCount=0;
    private static CopyOnWriteArrayList<WebSockTest> webSocketSet=new CopyOnWriteArrayList<WebSockTest>();
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为"+getOnlineCount());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息:"+message);
//        群发消息
        for (WebSockTest item:webSocketSet){
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("发生错误!");
        throwable.printStackTrace();
    }
//   下面是自定义的一些方法
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    public static synchronized int getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        WebSockTest.onlineCount++;
    }
    public static synchronized void subOnlineCount(){
        WebSockTest.onlineCount--;
    }
}

四、springboot要注入ServerEndpointExporter 

注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。 要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter, 因为它将由容器自己提供和管理。

WebSocketConfig.java

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。

全部的代码就是这样,没有其他的配置,都在这儿了。完成代码后,打开两个浏览器,可以看到两个页面可以实现即时通讯的功能。(如下图效果!)

我这些内容也是看了好几篇博客,现在写出来记在自己的小本本上,免得下次还得搜其他人的

<think>好的,我现在需要解决用户提出的两个问题:WebSocket握手错误(Unexpectedresponse code:400)和Three.js中球体旋转无效的问题。先拆分问题,逐个分析。 首先,WebSocket的400错误。用户提到在开发环境正常,但测试和生产环境出现错误,生产环境用了Nginx反向代理。引用[1]和[4]都涉及Nginx配置问题,特别是WebSocket代理的设置。常见原因是Nginx没有正确配置Upgrade和Connection头,导致WebSocket握手失败。检查用户的Nginx配置,发现虽然已经设置了proxy_set_header Upgrade和Connection,但可能缺少其他必要配置,比如超时设置或协议版本。另外,引用[2]提到SpringBoot项目中需要添加ServerEndpointExporter的Bean,但用户的问题可能更多在于生产环境的代理配置,而非后端代码。接下来是Three.js球体旋转的问题。用户代码中设置了sphere.rotation.z,但球体仍然垂直于XY轴。根据之前的回答,可能原因是矩阵未更新或坐标系问题。用户已经调用了updateMatrix,但可能需要使用updateMatrixWorld或者检查旋转轴是否正确。此外,使用Group容器包裹对象可能更有效,或者检查几何体的创建方式是否有误。现在需要将这两个问题的解决方案整合,确保回答结构清晰,步骤明确。同时,生成相关问题,并正确引用参考资料。</think>### WebSocket 握手错误 (400) 解决方案 #### **1. Nginx 代理配置优化** ```nginx server { listen 80; server_name yourdomain.com; # 强制 WebSocket 协议升级 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # 超时设置(单位:秒) proxy_connect_timeout 60; proxy_read_timeout 600; proxy_send_timeout 600; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` 关键配置项说明: - `proxy_http_version 1.1`:强制使用 HTTP/1.1 协议[^4] - `Upgrade $http_upgrade`:传递协议升级头 - `Connection "upgrade"`:标记连接类型为升级模式 #### **2. Spring Boot 后端验证** 确保已添加 WebSocket 端点暴露器: ```java @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); // 必须注入该 Bean[^2] } } ``` #### **3. 客户端连接验证** 前端代码需匹配实际路径: ```javascript // 生产环境应使用 wss 协议 const socket = new WebSocket("wss://yourdomain.com/websocket"); ``` --- ### Three.js 球体旋转失效解决方案 #### **1. 矩阵更新机制** 修正后的旋转代码: ```javascript sphere.rotation.z = Math.PI/2; sphere.updateMatrixWorld(true); // 强制更新世界坐标系[^1] ``` #### **2. 四元数旋转替代方案** ```javascript const axis = new THREE.Vector3(0, 0, 1); // Z 轴单位向量 const angle = Math.PI/2; // 旋转角度 sphere.quaternion.setFromAxisAngle(axis, angle); ``` #### **3. 坐标系验证工具** ```javascript // 添加三维坐标系可视化辅助 const axesHelper = new THREE.AxesHelper(10); scene.add(axesHelper); // X:红,Y:绿,Z:蓝[^1] ``` #### **4. 旋转性能公式** 计算旋转后的坐标变换: $$ \begin{bmatrix} x' \\ y' \\ z' \end{bmatrix} = \begin{bmatrix} \cosθ & -\sinθ & 0 \\ \sinθ & \cosθ & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \end{bmatrix} $$ 其中 $θ$ 为绕 Z 轴的旋转角度 --- ### 错误排查对照表 | 现象 | 检测点 | 解决方案 | |------|--------|----------| | WebSocket 400 | Nginx 日志检查 `tail -f /var/log/nginx/error.log` | 修正协议升级头配置[^4] | | 球体无旋转 | 检查 `axesHelper` 的 Z 轴方向 | 修正旋转轴向量[^1] | | 连接超时 | 抓包分析 `tcpdump -i eth0 port 80` | 调整代理超时参数[^4] | ---
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值