项目名 chat 端口号8080 访问路径:"ws://localhost:8080/websocket" jdk :1.8, Maven配置的tomcat是tomcat8, POM.xml添加了javax.websocket-api,spring-websocket和javax.servlet-api(provided)依赖。web.xml里的<url-pattern/>为"/", 访问Controller路径正常。访问websocket路径报错:Error during WebSocket handshake: Unexpected response code: 400 .
不知道 websocket路径 是不是被 DispatcherServlet被拦截了?还是url有问题。 请坛友帮忙解答,谢谢。
<build>
<finalName>chat</finalName>
<!-- 配置插件 -->
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<port>8080</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
后端代码:
@ServerEndpoint(value = "/websocket", configurator = SocketConfigurator.class)
public class WebServer {
@OnOpen
public void open(Session session){
System.out.println("OPEN is running");
}
@OnMessage
public void receiveMessage(String message, Session session){
System.out.println(" send Message .. " +message);
session.getAsyncRemote().sendText(message);
}
@OnClose
public void close(){
System.out.println("Close is running ...");
}
}
public class SocketConfigurator extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put("ClientIP", httpSession.getAttribute("ClientIPadd"));
}
}
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>WebSocket 客户端</title>
</head>
<body>
<div>
<input type="button" id="btnConnection" value="连接" />
<input type="button" id="btnClose" value="关闭" />
<input type="button" id="btnSend" value="发送" />
</div>
<script src="http://code.jquery.com/jquery-3.2.1.js"integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
var socket;
if(typeof(WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
}
$("#btnConnection").click(function() {
//实现化WebSocket对象,指定要连接的服务器地址与端口
socket = new WebSocket("ws://localhost:8080/websocket");
//打开事件
socket.onopen = function() {
alert("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
alert(msg.data);
};
//关闭事件
socket.onclose = function() {
alert("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("发生了错误");
}
});
//发送消息
$("#btnSend").click(function() {
socket.send("这是来自客户端的消息" + location.href + new Date());
});
//关闭
$("#btnClose").click(function() {
socket.close();
});
</script>
</body>
</html>
Java
Apache Tomcat
Spring
tomcat7建立websocket用的是BIO,建议使用tomcat9, 9更新了websocket的实现为NIO2