介绍
netty-socketio是socket.io使用Java语言基于Netty网络库编写的WebSocket库.功能非常强大,简单易用,稳定可靠.
- <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>