基於Netty實現的netty-socketio實現WebSocket

介紹

netty-socketio是socket.io使用Java語言基於Netty網絡庫編寫的WebSocket庫.功能很是強大,簡單易用,穩定可靠.javascript

<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.7.14</version>
</dependency>

後端使用Demo

1.配置SocketIOServer

@Value("${my.server.host}")
private String host;
@Value("${my.server.port}")
private Integer port;

@Bean
public SocketIOServer socketIOServer() {
    Configuration config = new Configuration();
    config.setOrigin(null);   // 注意若是開放跨域設置,須要設置爲null而不是"*"
    config.setPort(this.port);
    config.setSocketConfig(new SocketConfig());
    config.setWorkerThreads(100);
    config.setAuthorizationListener(handshakeData -> true);
    final SocketIOServer server = new SocketIOServer(config);
    server.start();
    return server;

}

@Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketIOServer){
    return new SpringAnnotationScanner(socketIOServer);
}

2.鏈接,斷開鏈接,推送消息,接收消息

@OnConnect
public void onConnect(SocketIOClient client) {
    String no0 = client.getHandshakeData().getSingleUrlParam("no");
    logger.info("工號爲no = {}的用戶創建WebSocket鏈接", no0);
    int no = 0;
    try {
        no = Integer.parseInt(no0);
    } catch (Exception e) {
        logger.error("創建WebSocket鏈接,獲取工號信息異常");
    }
    if (no != 0) {
        noClientMap.put(no, client);
    }
}


@OnDisconnect
public void onDisConnect(SocketIOClient client) {
    String no0 = client.getHandshakeData().getSingleUrlParam("no");

    logger.info("工號爲no = {}的用戶斷開WebSocket鏈接", no0);
    
    int no = 0;
    try {
        no = Integer.parseInt(no0);
    } catch (Exception e) {
        logger.error("創建WebSocket鏈接,獲取工號信息異常");
    }
    if (no != 0) {
        noClientMap.remove(no, client);
    }

}


@OnEvent(value = "noEvent")
public void onEvent(SocketIOClient client, Integer data, AckRequest request) {
    logger.info("工號no = {}的用戶推送消息", data    );
    if (data != null && data > 0) {
        noClientMap.put(data, client);
    }
}



@Override
public void toOne(int no, String eventName, Object data) {
    SocketIOClient socketIOClient = noClientMap.get(no);
    if (socketIOClient != null) {
        try {
            // 推送消息即爲調用SocketIOClient的sendEvent方法
            socketIOClient.sendEvent(eventName, data);
        } catch (Exception e) {
            logger.info("推送消息給工號爲no = {}的用戶異常", no, e.getMessage());
        }
    }

}

@Override
public void toAll(Object data) {
    for (Integer no : noClientMap.keySet()) {
        toOne(no, NettyEventEnum.RUNNING_TASK.getName(), data);
    }
}

前端Demo代碼

1.引入socket.io文件

<script src="https://cdn.bootcss.com/socket.io/2.1.0/socket.io.js"></script>

2.創建鏈接、斷開鏈接、接收消息、推送消息

<script >
      
      var username = 'username';
      var socket = io.connect('http://localhost:12350?no=' + username);

      socket.on('connect', function () {
          console.log('鏈接')
      });

      socket.on('runningTask', function (data) {
          console.log("收到全服數據")
          console.log(data);
      });


      socket.on('taskResult', function (data) {
          console.log("收到我的數據")
          console.log(data);
          
      });

        // 能夠是任意類型的數據,這裏用了一個json對象,後端有對應的實體類
        var jsonObject = {
            "username": "username1",
            "to": 2
        };
        socket.emit('messageevent', jsonObject);


      socket.on('disconnect', function () {
          console.log("斷開")
      });
  
  </script>
相關文章
相關標籤/搜索