当前位置:   article > 正文

netty-socketio概述_netty socketio

netty socketio

时刻不忘拜读API:vue.js 官方文档拜读

git源代码地址: Socket.IO-client Java

api文档地址: socket.io(node.js接口)

值得深入研究的API接口文档:  【javascript】 node.js版本的API

netty-socketio 概述

         netty-socketio是一个开源的Socket.io服务器端的一个java的实现,它基于Netty框架,可用于服务端推送消息给客户端。

        说到服务端推送技术,一般会涉及WebSocket,WebSocket是HTML5最新提出的规范,虽然主流浏览器都已经支持,但仍然可能有不兼容的情况,为了兼容所有浏览器,给程序员提供一致的编程体验,

        SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口,也就是说,使用SocketIO时不用担心兼容问题,底层会自动选用最佳的通信方式

       

       

            netty-socketio 示例demo

                  pom.xml

                  

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.corundumstudio.socketio</groupId>
  8. <artifactId>netty-socketio</artifactId>
  9. <version>1.7.18</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.projectlombok</groupId>
  13. <artifactId>lombok</artifactId>
  14. <version>1.18.4</version>
  15. <scope>provided</scope>
  16. </dependency>
  17. </dependencies>

                 启动类 NettySocketioApplication

                

  1. @SpringBootApplication
  2. @Slf4j
  3. public class NettySocketioApplication implements CommandLineRunner {
  4. public static void main(String[] args) {
  5. SpringApplication.run(NettySocketioApplication.class, args);
  6. }
  7. @Autowired
  8. private SocketIOServer socketIOServer;
  9. @Override
  10. public void run(String... strings) {
  11. socketIOServer.start();
  12. log.info("socket.io启动成功!");
  13. }
  14. }

  Message  消息类

  1. @Data
  2. public class Message {
  3. private String id; // 消息ID
  4. private String msg; // 消息内容
  5. private Date sendDate; // 发送日期
  6. }

配置类 NettySocketioConfig

    

  1. @Configuration
  2. public class NettySocketioConfig {
  3. /**
  4. * netty-socketio服务器
  5. */
  6. @Bean
  7. public SocketIOServer socketIOServer() {
  8. com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
  9. config.setHostname("localhost");
  10. config.setPort(9092);
  11. SocketIOServer server = new SocketIOServer(config);
  12. return server;
  13. }
  14. /**
  15. * 用于扫描netty-socketio的注解,比如 @OnConnect@OnEvent
  16. */
  17. @Bean
  18. public SpringAnnotationScanner springAnnotationScanner() {
  19. return new SpringAnnotationScanner(socketIOServer());
  20. }
  21. }

消息处理器 MessageEventHandler

 

  1. @Component
  2. @Slf4j
  3. public class MessageEventHandler {
  4. @Autowired
  5. private SocketIOServer socketIoServer;
  6. public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();
  7. /**
  8. * 客户端连接的时候触发
  9. *
  10. * @param client
  11. */
  12. @OnConnect
  13. public void onConnect(SocketIOClient client) {
  14. String mac = client.getHandshakeData().getSingleUrlParam("mac");
  15. //存储SocketIOClient,用于发送消息
  16. socketIOClientMap.put(mac, client);
  17. //回发消息
  18. client.sendEvent("message", "onConnect back");
  19. log.info("客户端:" + client.getSessionId() + "已连接,mac=" + mac);
  20. }
  21. /**
  22. * 客户端关闭连接时触发
  23. *
  24. * @param client
  25. */
  26. @OnDisconnect
  27. public void onDisconnect(SocketIOClient client) {
  28. log.info("客户端:" + client.getSessionId() + "断开连接");
  29. }
  30. /**
  31. * 客户端事件
  32. *
  33. * @param client  客户端信息
  34. * @param request 请求信息
  35. * @param data  客户端发送数据
  36. */
  37. @OnEvent(value = "messageevent")
  38. public void onEvent(SocketIOClient client, AckRequest request, Message data) {
  39. log.info("发来消息:" + data);
  40. //回发消息
  41. client.sendEvent("messageevent", "我是服务器都安发送的信息");
  42. //广播消息
  43. sendBroadcast();
  44. }
  45. /**
  46. * 广播消息
  47. */
  48. public void sendBroadcast() {
  49. for (SocketIOClient client : socketIOClientMap.values()) {
  50. if (client.isChannelOpen()) {
  51. client.sendEvent("Broadcast", "当前时间", System.currentTimeMillis());
  52. }
  53. }
  54. }
  55. }

html 页面

  

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
  6. <title>websocket-java-socketio</title>
  7. <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
  8. </head>
  9. <body>
  10. <h1>Socket.io Test</h1>
  11. <div><p id="status">Waiting for input</p></div>
  12. <div><p id="message">hello world!</p></div>
  13. <button id="connect" onClick='connect()'/>Connect</button>
  14. <button id="disconnect" onClick='disconnect()'>Disconnect</button>
  15. <button id="send" onClick='send()'/>Send Message</button>
  16. </body>
  17. <script type="text/javascript">
  18. /**
  19. * 前端js的 socket.emit("事件名","参数数据")方法,是触发后端自定义消息事件的时候使用的,
  20. * 前端js的 socket.on("事件名",匿名函数(服务器向客户端发送的数据))为监听服务器端的事件
  21. **/
  22. var socket = io.connect("http://localhost:9092?mac=2");
  23. var firstconnect = true;
  24. function connect() {
  25. if(firstconnect) {
  26. //socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
  27. //socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
  28. //+ nextRetry + " seconds"); });
  29. //socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
  30. //firstconnect = false;
  31. } else {
  32. socket.socket.reconnect();
  33. }
  34. }
  35. //监听服务器连接事件
  36. socket.on('connect', function(){ status_update("Connected to Server"); });
  37. //监听服务器关闭服务事件
  38. socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
  39. //监听服务器端发送消息事件
  40. socket.on('messageevent', function(data) {
  41. message(data)
  42. //console.log("服务器发送的消息是:"+data);
  43. });
  44. //断开连接
  45. function disconnect() {
  46. socket.disconnect();
  47. }
  48. function message(data) {
  49. document.getElementById('message').innerHTML = "Server says: " + data;
  50. }
  51. function status_update(txt){
  52. document.getElementById('status').innerHTML = txt;
  53. }
  54. function esc(msg){
  55. return msg.replace(/</g, '<').replace(/>/g, '>');
  56. }
  57. //点击发送消息触发
  58. function send() {
  59. console.log("点击了发送消息,开始向服务器发送消息")
  60. var msg = "我很好的,是的.";
  61. socket.emit('messageevent', {msgContent: msg});
  62. };
  63. </script>
  64. </html>

执行输出

运行 SpringBoot 服务器

>  mvn spring-boot:run

点击网页按钮

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/83546
推荐阅读
相关标签
  

闽ICP备14008679号