spring boot 注解方式实现websocket
2018-07-19 09:51
375 查看
1,pom文件引入websocket包:
[code] <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2,启动类添加@EnableWebSocket注解,启动支持websocket
3,创建websocket配置类
[code] 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(); } }
4,创建WebSocket实现@ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}")注解中的路径是前端发送请求的路径,同时 从路径里面获取前端参数
[code] import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}") @Component @Slf4j public class WebSocketServer { private static int onlineCount=0; private static ConcurrentHashMap<String,ConcurrentHashMap<String,WebSocketServer>> webSocketMap=new ConcurrentHashMap<String,ConcurrentHashMap<String, WebSocketServer>>(); private Session session; private String novelId=""; private String userSessionId=""; @OnOpen public void onOpen(Session session, @PathParam("novelId") String novelId ,@PathParam("userSessionId") String userSessionId,EndpointConfig config){ this.session=session; this.novelId=novelId; this.userSessionId=userSessionId; ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId); if (novelMap ==null){ ConcurrentHashMap<String, WebSocketServer> noticeMap= new ConcurrentHashMap<>(); noticeMap.put(userSessionId,this); webSocketMap.put(novelId,noticeMap); }else{ WebSocketServer webSocketServer = novelMap.get(userSessionId); if (webSocketServer==null){ novelMap.put(userSessionId,this); webSocketMap.put(novelId,novelMap); } } addOnlineCount(); log.info("webSocket连接成功------》当前在线人数:"+getOnlineCount()); } public static void sendInfo(String message,@PathParam("novelId") String novelId,@PathParam("userSessionId") String userSessionId) { Iterator<Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>>> iterator = webSocketMap.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>> next = iterator.next(); if (next.getKey().equals(novelId)){ ConcurrentHashMap<String, WebSocketServer> value = next.getValue(); Enumeration<String> keys = value.keys(); while (keys.hasMoreElements()){ String s = keys.nextElement(); value.get(s).sendMessage(message); } } } } public void sendMessage(String message){ try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("WebSocket推送消息异常:{}",e); } } @OnClose public void onClose() { ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId); if (novelMap ==null){ webSocketMap.remove(novelId); }else{ novelMap.remove(userSessionId); webSocketMap.put(novelId,novelMap); } subOnlineCount(); log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
附上前端测试代码
[code]<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>websocket测试</title> <script src="http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script> <script type="text/javascript"> function WebSocketTest() { var ws=null; if ("WebSocket" in window) { console.log("您的浏览器支持 WebSocket!"); // 打开一个 web socket ws = new WebSocket("ws://127.0.0.1:8080/websocket/test/test"); } else { console.log("浏览器不支持 WebSocket!"); // 浏览器不支持 WebSocket } ws.onopen = function() { console.log("WebSocket------>已打开"); }; ws.onmessage = function (msg) { console.log(msg.data); console.log("WebSocket------->发现消息"); }; ws.onclose = function() { // 关闭 websocket console.log("连接已关闭..."); }; } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">运行 WebSocket</a> </div> </body> </body> </html>
阅读更多
相关文章推荐
- websocket的两种实现方式:1基于注解,2与spring整合
- springboot aop 自定义注解方式实现一套完善的日志记录(完整源码)
- springboot整合tomcat自带的websocket实现在线聊天及象棋网页对战功能
- spring boot框架学习之重要注解3注解方式读取外部资源配置文件
- Spring知识点总结(三)之注解方式实现IOC和DI
- 基于springboot搭建dubbo框架(注解和xml配置两种方式)
- 注解方式实现spring-aop
- 用Spring Aop方式拦截自定义注解的实现
- Spring 注解方式实现的AOP
- SpringBoot入门-17(springboot集成mybatis注解形式实现ID自动增长)
- Spring学习笔记(三)Spring注解方式实现AOP
- 以用户登录、注册、添加删除修改为例,解析jdbcTemplate使用方式以及spring注解实现CRUD
- 转:Spring AOP 注解方式实现的一些“坑”
- BasicDAO与SpringDAO区别,使用Hibernate验证,注解方式实现主键自增,注解方式注入外键(一对多)
- Spring的AOP分为注解和配置两种方式实现
- 使用Spring的注解方式实现AOP
- Jeecg中通过Spring_AOP+注解方式实现日志的管理
- spring mybatis 用注解方式实现动态切切换数据源
- spring boot框架学习学前掌握之重要注解(2)-通过java的配置方式进行配置spring
- Spring使用注解的方式实现AOP