netty-socketio+spring boot 长链接 实时通信 消息推送

越嘉茂
2023-12-01

**

Springboot 集成 netty-socketio, 基于 Netty 实现, 进行 Sockcet 长连接,进行实时通讯,消息推送。

**

1、maven 配置

    	<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.49.Final</version>
        </dependency>
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.18</version>
        </dependency>

2、NettyServer

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
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;

/**
 * @author hua
 */
@Component
@Slf4j
public class NettyServer {
    public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();

    /**
     * 客户端连接的时候触发
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String mac = client.getHandshakeData().getSingleUrlParam("mac");
        //存储SocketIOClient,用于发送消息
        socketIOClientMap.put(mac, client);
        //回发消息
        log.info("客户端:" + client.getSessionId() + "已连接,mac=" + mac);
    }

    /**
     * 客户端事件
     * @param data    客户端发送数据
     */
    @OnEvent(value = "messageevent") //messageevent与客户端事件名称一致
    public void onEvent( String data) {
        log.info("发来消息:" + data);
        //回发消息
        for (SocketIOClient client : socketIOClientMap.values()) {
            if (client.isChannelOpen()) {
                client.sendEvent("messageevent", data); //发送消息、
                client.sendEvent("Broadcast", "当前时间", System.currentTimeMillis());//广播消息
            }
        }
    }
}

3、启动类配置

@Slf4j
@SpringBootApplication 
public class Application implements CommandLineRunner {
    @Autowired
    private SocketIOServer socketIOServer;

    public static void main(String[] args) {
        SpringApplication.run(XiaoyuAdminApplication.class, args);
        log.info("application start success startTime:{}", DateUtil.getDateTime());
    }

    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        socketIOServer.start();
    }

    /**
     * netty-socketio服务器
     */
    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname("0.0.0.0");  
        config.setPort(9092);
        SocketConfig socketConfig = config.getSocketConfig();
        if(!socketConfig.isReuseAddress()){
            socketConfig.setReuseAddress(true);
            log.info("是否绑定了:{}", socketConfig.isReuseAddress());
        }
        return new SocketIOServer(config);
    }

    /**
     * 用于扫描netty-socketio的注解,比如 @OnConnect、@OnEvent
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner() {
        return new SpringAnnotationScanner(socketIOServer());
    }
}

4、前端

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>websocket-java-socketio</title>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
</body>
 
<script type="text/javascript">
	 var test = window.location.host;
	  //  192.168.0.101:8183
	  var host;
	  if(test.indexOf(":") != -1){
	    var arr = test.split(':');
	    host = arr[0]
	  }else{
	    host = test
	  }
    var socket = io.connect(host+":9092?mac="++ Math.random());
 
    //监听服务器连接事件
    socket.on('connect', function(){ 
    	socket.emit('simple', "hello server");
    });
    //监听服务器关闭服务事件
    socket.on('disconnect', function(){ 
    	
    });
    
    //监听服务器端发送消息事件 messageevent 要与后台声明的事件名称一致
    socket.on('messageevent', function(data) {
		console.log("服务器发送的消息是:", data);
    });
</script>
</html>


 类似资料: