小灰也在学 | Websocket技术的Java实现(上篇)
在上周简单地介绍了一下长轮询、短轮询和Websocket。今天我们一起了解怎么用Java来实现Websocket吧~
引入依赖
<!--websocket支持包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
创建配置类WebSocketConfig
ServerEndpointExporter是由Spring官方提供的标准实现,用于扫描ServerEndpointConfig配置类和@ServerEndpoint注解实例。
如果使用内置的tomcat容器,那么必须用注入ServerEndpointExporter ;
如果使用外置容器部署war包,那么不需要提供ServerEndpointExporter ,扫描服务器的行为将交由外置容器处理。
@Configurationpublic class WebSocketConfig {/*** 如果使用Springboot默认内置的tomcat容器,则必须注入ServerEndpoint的bean;* 如果使用外置的web容器,则不需要提供ServerEndpointExporter,下面的注入可以注解掉*/@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}}
创建WebSocketServer
在websocket协议下,后端服务器相当于ws里面的客户端,需要用@ServerEndpoint指定访问路径,并使用@Component注入容器。
注:@ServerEndpoint:当ServerEndpointExporter类通过Spring配置进行声明并被使用,它将会去扫描带有@ServerEndpoint注解的类。被注解的类将被注册成为一个WebSocket端点。所有的配置项都在这个注解的属性中 ( 如:@ServerEndpoint("/ws") )
(value = "/ws/{sid}")public class WebSocketServer {private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;//使用map对象优化,便于根据sid来获取对应的WebSocketprivate static ConcurrentHashMap<String,WebSocketServer> websocketMap = new ConcurrentHashMap<>();//接收用户的sid,指定需要推送的用户private String sid;/**连接成功后调用的方法*/public void onOpen(Session session,@PathParam("sid") String sid) {this.session = session;//webSocketSet.add(this); //加入set中websocketMap.put(sid,this); //加入map中addOnlineCount(); //在线数加1log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());this.sid=sid;try {sendMessage("连接成功");} catch (IOException e) {log.error("websocket IO异常");}}/**连接关闭调用的方法*/public void onClose() {if(websocketMap.get(this.sid)!=null){//webSocketSet.remove(this); //从set中删除websocketMap.remove(this.sid); //从map中删除subOnlineCount(); //在线数减1log.info("有一连接关闭!当前在线人数为" + getOnlineCount());}}/**收到客户端消息后调用的方法,根据业务要求进行处理,这里就简单地将收到的消息直接群发推送出去*/public void onMessage(String message, Session session) {log.info("收到来自窗口"+sid+"的信息:"+message);if(StringUtils.isNotBlank(message)){for(WebSocketServer server:websocketMap.values()) {try {server.sendMessage(message);} catch (IOException e) {e.printStackTrace();continue;}}}}/**发生错误时的回调函数*/public void onError(Session session, Throwable error) {log.error("发生错误");error.printStackTrace();}/**实现服务器主动推送消息*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/**群发自定义消息(用set会方便些)*/public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {log.info("推送消息到窗口"+sid+",推送内容:"+message);if(StringUtils.isNotBlank(message)){for(WebSocketServer server:websocketMap.values()) {try {// sid为null时群发,不为null则只发一个if (sid == null) {server.sendMessage(message);} else if (server.sid.equals(sid)) {server.sendMessage(message);}} catch (IOException e) {e.printStackTrace();continue;}}}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}}
websocket调用
方式1:提供接口进行消息推送
用户调用接口,主动发请求到后端,后端接收后再主动推送给指定/全部用户。
("/websocket")public class WebSocketController {//页面请求("/socket/{cid}")public ModelAndView socket( String cid) {ModelAndView mav=new ModelAndView("/socket");mav.addObject("cid", cid);return mav;}//推送数据接口("/socket/push/{cid}")public Map<String,Object> pushToWeb( String cid, String message) {Map<String,Object> result = new HashMap<>();try {WebSocketServer.sendInfo(message,cid);result.put("status","success");} catch (IOException e) {e.printStackTrace();result.put("status","fail");result.put("errMsg",e.getMessage());}return result;}}
方法2:由前端指定ws调用网址直接使用
<html><head><meta charset="utf-8"><title>websocket通讯</title></head><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script><script>var socket;function openSocket() {if(typeof(WebSocket) == "undefined") {console.log("您的浏览器不支持WebSocket");}else{console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接//等同于socket = new WebSocket("ws://localhost:9010/javatest/ws/25");//var socketUrl="${request.contextPath}/ws/"+$("#userId").val();var socketUrl="http://localhost:9010/javatest/ws/"+$("#userId").val();socketUrl=socketUrl.replace("https","ws").replace("http","ws");console.log(socketUrl)socket = new WebSocket(socketUrl);//打开事件socket.onopen = function() {console.log("websocket已打开");//socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件socket.onmessage = function(msg) {console.log(msg.data);//发现消息进入 开始处理前端触发逻辑};//关闭事件socket.onclose = function() {console.log("websocket已关闭");};//发生了错误事件socket.onerror = function() {console.log("websocket发生了错误");}}}function sendMessage() {if(typeof(WebSocket) == "undefined") {console.log("您的浏览器不支持WebSocket");}else {console.log("您的浏览器支持WebSocket");console.log('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');socket.send('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');}}</script><body><p>【userId】:<div><input id="userId" name="userId" type="text" value="11"/></div><p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="22"/></div><p>【toUserId内容】:<div><input id="contentText" name="contentText" type="text" value="abc"/></div><p>【操作】:<div><input type="button" onclick="openSocket()"/>开启socket</div><p>【操作】:<div><input type="button" onclick="sendMessage()"/>发送消息</div></body></html>
