Spring Boot - WebSocket 握手期间出错

Posted

技术标签:

【中文标题】Spring Boot - WebSocket 握手期间出错【英文标题】:Spring Boot - Error during WebSocket handshake 【发布时间】:2019-07-01 21:24:48 【问题描述】:

当我尝试在我的 Spring Boot 应用程序中使用 WebSocket 时,出现此错误:“WebSocket 连接到 'ws://localhost:8080/Moda/chatroomServerEndpoint' 失败:WebSocket 握手期间出错:意外响应代码:400”(默认.html-第 11 行).. 我的目标:通过两个不同的选项卡发送消息(例如:在 Google Chrome 中)请帮助我!谢谢...

默认.html

<!<!DOCTYPE html>
<html lang="en">
	

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Deneme</title>

<script type = "text/javascript">

	var websocket = new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint");
	websocket.onmessage = function processMessage(message) 
		var jsonData = JSON.parse(message.data);
		if(jsonData.message != null) messagesTextArea.value += jsonData.message + "\n";
	
	function sendMessage()
		websocket.send(messageText.value);
		messageText.value = "";
	

</script>

	</head>
	
	 <body>
<textarea id="messagesTextArea" readonly = "readonly" rows="10" cols="45"></textarea><br/>
<input type = "text" id="messageText" size="50" /><input type="button" value="Send" onclick="sendMessage();" />
   
	</body>
  
  </html>

ModaApplication.java

package com.moda;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.socket.config.annotation.EnableWebSocket;



import com.moda.videochat.MyWebSocketConfigurator;

@Configuration
@EnableAutoConfiguration
@ServerEndpoint("/chatroomServerEndpoint")
public class ModaApplication 

	public static void main(String[] args) 
		SpringApplication.run(ModaApplication.class, args);
	
	static Set<Session> chatroomUsers = Collections.synchronizedSet(new HashSet<Session>());
	
	@OnOpen
	public void handleOpen(Session userSession)
	
		chatroomUsers.add(userSession);
	
	
	@OnMessage
	public void handleMessage(String message, Session userSession) throws IOException 
		String username = (String) userSession.getUserProperties().get("username");
		if(username == null)
		
			userSession.getUserProperties().get("username");
			userSession.getBasicRemote().sendText(buildJsonData("System","you are now connected as " + message));
		
		else
		
			Iterator<Session> iterator = chatroomUsers.iterator();
			while(iterator.hasNext()) iterator.next().getBasicRemote().sendText(buildJsonData(username,message));
		
	
	
	@OnClose
	public void handleClose(Session userSession)
	
		chatroomUsers.remove(userSession);
	
	
	private String buildJsonData(String username, String message)
	
		JsonObject jsonObject = Json.createObjectBuilder().add("message",username+": "+message).build();
		StringWriter stringWriter = new StringWriter();
		try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) jsonWriter.write(jsonObject);
		return null;
	

【问题讨论】:

【参考方案1】:

试试

new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint/websocket");

而不是

`new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint");`

还要确保设置.setAllowedOrigins("*")

【讨论】:

如何设置 .setAllowedOrigins("*") ?可以给样品吗? 我想他的意思是在 WebsocketBrokerConfiguration 类中添加该方法调用,在 registerStompEndpoints 类方法中,如下所示:registry.addEndpoint("/vrp-websocket") .setAllowedOrigins("*") .withSockJS();

以上是关于Spring Boot - WebSocket 握手期间出错的主要内容,如果未能解决你的问题,请参考以下文章

玩转spring boot——websocket

Spring Boot之WebSocket

Spring boot + Websocket

Spring Boot教程32——WebSocket

Spring Boot整合WebSocket实现实时消息推送

Spring Boot整合WebSocket实现实时消息推送