编辑器:idea。tomcat是springboot内置的tomcat,一开始出现
websocket failed: Error during WebSocket handshake: Unexpected response
这个问题的原因是,我一开始在项目中没有在注入ServerEndpointExporter ,后来注入后就能完整的运行了。
下面开始简单的实现过程:
项目使用springboot
页面:
一、首先,创建springboot项目,在pox.xml中加入
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、创建一个页面index.html,前端跳转后端的一些必要代码
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text" value="1#10000" placeholder="发送的消息"/>
<button onclick="send()">发送消息</button>
<hr/>
<!--userno:发送消息人的编号-->
发送人:<div id="userno">123456</div>
接收人:<input type="text" id="usernoto"><br>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
var userno=document.getElementById('userno').innerHTML;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8089/websocket/"+userno);
}
else {
alert('当前浏览器 Not support websocket')
}
//发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容
// document.getElementById('message').innerHTML += ("发送人:"+userno+'<br/>'+"---"+message) + '<br/>';
// document.getElementById('message').style.color="red";
// var ToSendUserno=document.getElementById('usernoto').value; //接收人编号:4567
// message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
websocket.send(message);
}
//连接发生错误的回调方法
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(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
</script>
</html>
三、后端的socket处理
package com.yanzhiyi.manager.websocket;
import com.yanzhiyi.manager.mapper.CompetitionResourceBundleMapper;
import com.yanzhiyi.manager.mapper.WordPracticeFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* FileName: WebSocketServer
* Author: xuan zongjun
* Date: 2019/8/6 12:21
* Description: webSocket服务端
*/
@Component
@ServerEndpoint("/websocket/{userno}")
public class WebSocketServer {
private static int onlineCount = 0;
private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<String, WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session WebSocketsession;
//当前发消息的人员编号
private String userno = "";
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
public void setUserno(String userno) {
this.userno = userno;
}
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
System.out.println( param );
userno = param;//接收到发送消息的人员编号
this.WebSocketsession = WebSocketsession;
webSocketSet.put( param, this );//加入map中
addOnlineCount(); //在线数加1
System.out.println( "有新连接加入!当前在线人数为" + getOnlineCount() );
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息 消息格式为:1#123456格式,如果#前边是1,则#后面是竞赛资源包编号
* @param session 可选的参数
*/
//@SuppressWarnings("unused")
@OnMessage
public void onMessage(String message, Session session) {
System.out.println( "来自客户端的消息:" + message );
sendAll( message );
}
/**
* 给班级所有人发送消息
*
* @param message
*/
public void sendAll(String message) {
//遍历HashMap
for (String key : webSocketSet.keySet()) {
System.out.println( "key = " + key );
try {
//判断接收用户是否是当前发消息的用户
webSocketSet.get( key ).sendMessage( message );
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 给指定的人发送消息
*
* @param message
*/
//@OnMessage
//public void sendToUser(String message) {
// System.out.println( "给指定人发信息" );
// String sendUserno = message.split( "[|]" )[1];
// String sendMessage = message.split( "[|]" )[0];
// try {
// System.out.println( "webSocketSet.get(sendUserno)" + webSocketSet.get( sendUserno ) );
// if (webSocketSet.get( sendUserno ) != null) {
// webSocketSet.get( sendUserno ).sendMessage( "用户" + userno + ": 广播" + " <br/> " + sendMessage );
// } else {
// System.out.println( "当前用户不在线" );
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userno.equals( "" )) {
webSocketSet.remove( userno ); //从set中删除
subOnlineCount(); //在线数减1
System.out.println( "有一连接关闭!当前在线人数为" + getOnlineCount() );
}
}
/**
* 获取当前时间
*
* @return
*/
private String getNowTime() {
Date date = new Date();
DateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
String time = format.format( date );
return time;
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println( "发生错误" );
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.WebSocketsession.getBasicRemote().sendText( message );
}
}
四、springboot要注入ServerEndpointExporter
注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。 要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter, 因为它将由容器自己提供和管理。
WebSocketConfig.java
package com.yanzhiyi.manager.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* FileName: WebSocketConfig
* Author: xuan zongjun
* Date: 2019/8/8 9:54
* Description: webSocket测试
* 此类在spring boot 测试时需要,而在打成war包发布时,要注释掉,
* 因为:如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter, 因为它将由容器自己提供和管理。
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来