核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用。
javax javaee-api 7.0 provided
如果使用springboot的内置tomcat时,就不需要引入javaee-api了,spring-boot已经包含了。使用springboot的websocket功能要引入springboot的websocket组件。
org.springframework.boot spring-boot-starter-websocket 1.3.5.RELEASE
首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。
虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
My WebSocket
Welcome
在demo中集成websocket时一切正常,但当移植到工作中的正式项目上时启动报错,无法正常启动,是因为将websocket实现类放到了controller目录下,额外新建一个websocket目录,将实现类放进去即可正常启动
错误原因:ServerEndpointExporter需要外置tomcat容器运行环境,但平常我们都是使用SpringBoot内置tomcat,导致ServerEndpointExporter在运行时一直报错。
解决方案:在pom.xml文件中,排除SpringBoot自带的嵌入tomcat,添加外置的tomcat依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-tomcat
错误原因:使用拦截器或过滤器但没有对请求放行,特别是使用Spring Security或Shiro,很容易遗忘放行请求路径
解决方案:在相应的配置文件中放行请求路径
filterMap.put("/websocket/**", "anon");//开放webSocket路径
在页面维持期间,动态口令需要一直不断的向前端推送实时口令,但是何时断开以及是谁断开就成了一个问题
解决方式如下:
创建一个WebSocketConnectStatusController类,
在前端发起websocket请求前,由前端生成一个特定的长度的key,
(1)进入动态口令页面,首先调用doIn接口并传入key,该key由前端保留备用;后端使用静态map来存放key,并将value设为0。
(2)建立连接,同时在session中传入上一步生成的key
@RestController
@RequestMapping("/webSocketConnectStatus")
public class WebSocketConnectStatusController {
public static Map map = new HashMap<>();
@GetMapping("/doIn")
@ApiOperation(value = "doIn方法")
public String doIn(String key){
//System.out.println("调用了doIn---");
map.put(key,"0");
return "开始获取动态码了";
}
@GetMapping("/doOut")
@ApiOperation(value = "doOut方法")
public String doOut(String key){
//System.out.println("调用了doOut---");
map.put(key,"1");
return "改完状态了,动态码获取结束";
}
}
(3)当用户离开页面时,调用doOut接口,并传入之前保留的本次连接的key,后端将静态map中对应key的value更新为1,此时后端不再向前端推送新的口令,循环结束。
后端推送消息的具体逻辑如下:
@OnMessage
public void onMessage(String message, Session session) {
String key = session.getQueryString();//获取session中的key
try {
while ("0".equals(WebSocketConnectStatusController.map.get(key))){
Thread.sleep(1000);//每秒推送一次
sendMessage("生成你的动态码");
}
WebSocketConnectStatusController.map.remove(key);//清空本次链接的key
} catch (IOException e) {
System.out.println("IO异常");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
只有当循环结束时才能正常断开连接,否则会报IO异常
(4)断开连接