由于最近离开了一个前端,做java的我被上级布置了一个任务,建立一个实时的沟通的demo。在经过几天的调研,目前比较稳定且兼容比较高的是socket.io。其官网:https://socket.io/

在官网中可以看到其是服务器推荐nodejs。由于java的多年经验的背景,我通过netty-socketio仿一个nodejs的服务环境。

服务端的环境:

spring boot 2.6.3

netty-socketio 1.7.19

socketio-clinet 2.0.1

前端:

react 17

typescript 4.5

socketio 2.0.1

1. 加载依赖

<!-- https://mvnrepository.com/artifact/com.corundumstudio.socketio/netty-socketio -->
<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.7.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.socket/socket.io-client -->
<dependency>
    <groupId>io.socket</groupId>
    <artifactId>socket.io-client</artifactId>
    <version>2.0.1</version>
</dependency>
2. 编辑配置 application.properties
# netty socket io setting
socketio.host = 127.0.0.1
socketio.port = 9001
socketio.maxFramePayloadLength = 1048576
socketio.maxHttpContentLenght = 1048576
#设置socket连接数的大小 只监听一个端口boss线程组为1即可
socketio.bossCount = 1
socketio.workCount = 100
socketio.allowCustomRequests = true
socketio.upgradeTimeout = 1000000
socketio.pingTimeout = 60000000
socketio.pingInterval = 25000
server.port=8081
3.  编辑配置文件
package com.example.reqq.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.Transport;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: hett
 * @date: 2021/12/13 10:02
 */

@Configuration
public class SocketIOConfig {
@Value("${socketio.host}")
private String host;

    @Value("${socketio.port}")
private Integer port;

    @Value("${socketio.bossCount}")
private int bossCount;

    @Value("${socketio.workCount}")
private int workCount;

    @Value("${socketio.allowCustomRequests}")
private boolean allowCustomRequests;

    @Value("${socketio.upgradeTimeout}")
private int upgradeTimeout;

    @Value("${socketio.pingTimeout}")
private int pingTimeout;

    @Value("${socketio.pingInterval}")
private int pingInterval;

    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
//        socketConfig.setTcpNoDelay(true);
//        socketConfig.setSoLinger(0);
        socketConfig.setTcpKeepAlive(true);
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(host);
        config.setPort(port);
        config.setBossThreads(bossCount);
        config.setWorkerThreads(workCount);
        config.setAllowCustomRequests(allowCustomRequests);
        config.setUpgradeTimeout(upgradeTimeout);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);
//        config.setTransports(Transport.POLLING, Transport.WEBSOCKET);
//        config.setOrigin(":*:");
        return new SocketIOServer(config);
    }

@Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
    }
}
4. 编辑启动类
package com.example.reqq.service;

import com.corundumstudio.socketio.SocketIOServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author: hett
 * @date: 2021/12/13 15:31
 */
@Component
@Order(value=1)
@Slf4j
public class SocketRunner implements CommandLineRunner {
private final SocketIOServer server;

    @Autowired
    public SocketRunner(SocketIOServer server) {
this.server = server;
    }

@Override
    public void run(String... args) throws Exception {
log.info("--------------------前端socket.io通信启动成功!---------------------");
        server.start();
    }
}
5. 创建socketio消息处理
package com.example.reqq.service;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Component
public class SocketIOServiceImpl  {

private static int i=0;
    public static ConcurrentMap<String, SocketIOClient> socketIOClientMap =
new ConcurrentHashMap<>();

    //socket事件消息接收入口
    @OnEvent(value = "message_event") //value值与前端自行商定
    public void onEvent(SocketIOClient client, AckRequest ackRequest, String data) throws Exception {
log.info(data);
        client.sendEvent("connected", "已成功接收数据"); //向前端发送接收数据成功标识
        client.sendEvent("message_event", "已成功接收数据"); //向前端发送接收数据成功标识
    }

@OnEvent(value = "push_data_event")
public  void recieve(SocketIOClient client, AckRequest ackRequest, String data) {
log.info(data.toString());
        i++;
        client.sendEvent("myBroadcast","服务端接受数据"+i);
    }

//socket添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
log.info("--------------------客户端已断开连接--------------------");
        client.disconnect();
    }

//socket添加connect事件,当客户端发起连接时调用
    @OnConnect
    public void onConnect(SocketIOClient client) {
if (client != null)
        {
            HandshakeData client_mac = client.getHandshakeData();
            String mac = client_mac.getUrl();
            //存储SocketIOClient,用于向不同客户端发送消息
            socketIOClientMap.put(mac, client);

            log.info("--------------------客户端连接成功---------------------");
            client.sendEvent("connected", "已成功接收数据"); //向前端发送接收数据成功标识
            client.sendEvent("message_event", "已成功接收数据"); //向前端发送接收数据成功标识
        } else {
log.error("客户端为空");
        }
    }

/**
     * 广播消息 函数可在其他类中调用
     */
    public static void sendBroadcast(byte[] data) {
for (SocketIOClient client : socketIOClientMap.values()) { //向已连接的所有客户端发送数据,map实现客户端的存储
            if (client.isChannelOpen()) {
                client.sendEvent("message_event", data);
            }
        }
    }
}
6. 编辑客户端
package com.example.reqq.controller;

import cn.hutool.core.date.DateUtil;
import io.socket.client.IO;
import io.socket.client.Socket;
import lombok.extern.slf4j.Slf4j;

/**
 * <p> socket.io客户端 </p>
 *
 * @author : zhengqing
 * @description :  socket.emit:发送数据到服务端事件
 *                 socket.on: 监听服务端事件
 * @date : 2020/2/7 17:43
 */
@Slf4j
public class SocketIOClientLaunch {

public static void main(String[] args) {
// 服务端socket.io连接通信地址
        String url = "http://127.0.0.1:8888";
        try {
            IO.Options options = new IO.Options();
            options.transports = new String[]{"websocket","xhr-polling","jsonp-polling"};
            options.reconnectionAttempts = 2;
            // 失败重连的时间间隔
            options.reconnectionDelay = 1000;
            // 连接超时时间(ms)
            options.timeout = 500;
            // userId: 唯一标识 传给服务端存储
            final Socket socket = IO.socket(url + "?userId=2", options);

            socket.on(Socket.EVENT_CONNECT, args1 -> socket.send("hello..."));

            // 自定义事件`connected` -> 接收服务端成功连接消息
            socket.on("connected", objects -> log.debug("服务端:" + objects[0].toString()));

            // 自定义事件`push_data_event` -> 接收服务端消息
            socket.on("push_data_event", objects -> log.debug("服务端:" + objects[0].toString()));

            // 自定义事件`myBroadcast` -> 接收服务端广播消息
            socket.on("myBroadcast", objects -> log.debug("服务端:" + objects[0].toString()));

            socket.emit("chatevent","1230");

            socket.connect();

            int i =1;

            while (true) {
                Thread.sleep(3000);
                i++;
                // 自定义事件`push_data_event` -> 向服务端发送消息
                socket.emit("push_data_event", "发送数据 " + i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

7. 调试运行
服务端

 

 

客户端

springboot 使用netty 客服端向服务端 发送16进制数据_spring

 

 8. 通过react+ts访问

import React, {Component} from 'react';

const io = require('socket.io-client');



class App extends Component {

componentDidMount(): void {

const socket  = io("http://localhost:9001", {
reconnectionDelayMax: 10000,
            transports:['websocket']
        });

        console.log(socket);

        socket.on('connect', function() {
console.log("connect")
        });
        socket.on('connect_error', (error : any) => {
console.log(error)
        });

        socket.on('message_event', function(data : any) {
console.log("message_event")
console.log(data);
        });


        socket.emit("push_data_event","react发送的数据");

        socket.on("myBroadcast",function (message :any) {
console.log(message);
        })
    }

render() {
return (
<div>
              hett
</div>
        );
    }
}

export default App;
经过几天的探索和调试,一直出现连接不成功的问题。经过阅读官方文档和相关代码,最终debug原因:
Error: It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)

因为netty-socketio支持的客户端目前仅仅是v2.X版本。而由于目前sokcetio-client已经更新到v4.X。所以卸载干净最新的版本

springboot 使用netty 客服端向服务端 发送16进制数据_服务端_02

 

 安装socket.io-client v2版本

D:\react\reqq>npm install socket.io-client@2
最终package.json如下

springboot 使用netty 客服端向服务端 发送16进制数据_spring_03

 

 

9. react+ts测试之后

springboot 使用netty 客服端向服务端 发送16进制数据_客户端_04

 

 搞定~

探索前端的路上