SpringBoot中集成WebSocket通信实例

一、什么是WebSocket
  WebSocket是HTML5下一种新的协议(websocket是一个基于tcp的协议)

二、WebSocket的原理
websocket是一种全新的协议,不属于http无状态协议,是双向通信的全双工协议,协议名为"ws"。

 

三、SpringBoot中,集成WebSocket的过程

1、在项目工程的pom文件中导入websocket的jar包依赖;

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>

我的项目工程中使用的SpringBoot版本是2.2.6.RELEASE版本,这里也使用相同的版本。

 

2、增加WebSocketConfig配置类;

package com.cscecnf.construction.site.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

3、增加WebSocketServer服务类;

package com.cscecnf.construction.site.tower.crane.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{sid}")
@Slf4j
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;

/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;

/**
* 接收sid
*/
private String sid = "";

/**
* onOpen 连接建立成功调用的方法
* @param session session
* @param sid sid
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
//加入set中
webSocketSet.add(this);
//在线数加1
addOnlineCount();
log.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
this.sid = sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}

/**
* onClose 连接关闭调用的方法
*/
@OnClose
public void onClose() {
//从set中删除
webSocketSet.remove(this);
//在线数减1
subOnlineCount();
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}

/**
* onMessage 收到客户端消息后调用的方法
* @param message message
* @param session session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口" + sid + "的信息:" + message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* onError 发生错误
* @param session session
* @param error error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}

/**
* sendMessage 实现服务器主动推送
* @param message message
* @throws IOException IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}

/**
* sendInfo 群发自定义消息
* @param message message
* @param sid sid
* @throws IOException IOException
*/
public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口" + sid + ",推送内容:" + message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if (sid == null) {
item.sendMessage(message);
} else if (item.sid.equals(sid)) {
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}

public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}

public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
注意:该服务类不要放在controller目录下面,也不要放在service目录下面,可以放在一个新建的目录下面,总之不要被扫描到要进行代理调用。否则,启动工程的时候就会报错:

  java.lang.IllegalStateException: Failed to register @ServerEndpoint class: class com.cscecnf.construction.site.tower.crane.controller.WebSocketServer$$EnhancerBySpringCGLIB$$49bcac82
  at org.springframework.web.socket.server.standard.ServerEndpointExporter.registerEndpoint(ServerEndpointExporter.java:159)
  at org.springframework.web.socket.server.standard.ServerEndpointExporter.registerEndpoints(ServerEndpointExporter.java:134)
  at org.springframework.web.socket.server.standard.ServerEndpointExporter.afterSingletonsInstantiated(ServerEndpointExporter.java:112)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:899)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
  at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
  at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
  at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
  at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
  at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
  at com.cscecnf.construction.site.SmartConstructionSiteApplication.main(SmartConstructionSiteApplication.java:23)
  Caused by: javax.websocket.DeploymentException: Cannot deploy POJO class [com.cscecnf.construction.site.tower.crane.controller.WebSocketServer$$EnhancerBySpringCGLIB$$49bcac82]

  as it is not   annotated with @ServerEndpoint
  at org.apache.tomcat.websocket.server.WsServerContainer.addEndpoint(WsServerContainer.java:245)

 

4、信息推送,增加在controller目录下面增加Controller类;

 package com.cscecnf.construction.site.tower.crane.controller;

import com.cscecnf.construction.site.tower.crane.util.WebSocketServer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
/**
* socket 页面请求
* @param cid cid
* @return ModelAndView
*/
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav = new ModelAndView("/socket");
mav.addObject("cid", cid);
return mav;
}

/**
* pushToWeb 推送数据接口
* @param cid cid
* @param message message
* @return String
*/
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid, String message) {
try {
WebSocketServer.sendInfo(message, cid);
} catch (IOException e) {
e.printStackTrace();
return "error:" + cid + "#" + e.getMessage();
}
return "success:" + cid;
}
}

5、在浏览器的Console中执行websocket注册却报错了,实际上服务已经正常启动了,并且注册的地址也是正确的;
socket = new WebSocket("ws://192.168.19.1:8101/上下文根/websocket/20");

6、这个报错是因为请求的地址被SSO的过滤器拦截了,需要在项目工程的sso过滤器配置类中放行websocket的请求:

package com.cscecnf.construction.site.config;

import com.cscecnf.sso.client.SmartContainer;
import com.cscecnf.sso.client.filter.LoginFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SsoConfig {

@Value("${sso.server.url}")
private String serverUrl;
@Value("${sso.app.id}")
private String appId;
@Value("${sso.app.secret}")
private String appSecret;
@Value("${sso.check-auth}")
private Boolean checkAuth;

/**
* Web支持单点登录Filter容器
* @return
*/
@Bean
public FilterRegistrationBean<SmartContainer> smartContainer() {
SmartContainer smartContainer = new SmartContainer();
smartContainer.setServerUrl(serverUrl);
smartContainer.setAppId(appId);
smartContainer.setAppSecret(appSecret);
smartContainer.setCheckAuth(checkAuth);
// 忽略拦截URL,多个逗号分隔
smartContainer.setExcludeUrls("/websocket/*,/swagger-resources/*,/swagger-ui.html,/doc.html");
smartContainer.setFilters(new LoginFilter());
FilterRegistrationBean<SmartContainer> registration = new FilterRegistrationBean<>();
registration.setFilter(smartContainer);
registration.addUrlPatterns("/*");
registration.setOrder(1);
registration.setName("smartContainer");
return registration;
}

 7、再次在Console控制台中执行命令,可以成功注册到服务端了:

 

8、在页面发起websocket请求,即在页面中用js代码调用websocket;

var socket;
  if(typeof(WebSocket) == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  }else{
  console.log("您的浏览器支持WebSocket");
  //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  socket = new WebSocket("ws://192.168.19.1:8101/smart-construction-site/websocket/20");
  // 打开事件
  socket.onopen = function() {
    console.log("Socket 已打开");
    //socket.send("这是来自客户端的消息" + location.href + new Date());
  };
  // 获得消息事件
  socket.onmessage = function(msg) {
  console.log(msg.data);
  // 发现消息进入 开始处理前端触发逻辑
  };
  // 关闭事件
  socket.onclose = function() {
    console.log("Socket已关闭");
  };
  // 发生了错误事件
  socket.onerror = function() {
    alert("Socket发生了错误");
    // 此时可以尝试刷新页面
  }
  // 离开页面时,关闭socket
  // jquery1.8中已经被废弃,3.0中已经移除
  // $(window).unload(function(){
    // socket.close();
    //});
}

 

 9、向前端推送数据:http://192.168.19.1:8101/上下文根/checkcenter/socket/push/20?message=Hello

 

前端页面也已经收到消息

 

 

 


posted @ 2023-03-31 10:33  勇敢-的心  阅读(638)  评论(0编辑  收藏  举报