springboot+netty+socketio implements server push

Import dependencies

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

Server

public class Server {
    public static final ConcurrentHashMap<UUID, SocketIOClient> clients = new ConcurrentHashMap<UUID, SocketIOClient>();

    public static final CountDownLatch latch = new CountDownLatch(1);

    public void run() throws Exception {
        Configuration configuration = new Configuration();
        configuration.setHostname("127.0.0.1");//设置主机名
        configuration.setPort(12121);//设置监听的端口号
        SocketIOServer server = new SocketIOServer(configuration);//根据配置创建服务器对象

        server.addConnectListener(new ConnectListener() {//添加客户端连接监听器
            @Override
            public void onConnect(SocketIOClient client) {
                System.out.println("connected:SessionId=" + client.getSessionId());
                clients.put(client.getSessionId(), client);//保存客户端
            }
        });

        server.start();
        System.out.println("server started");
        
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Random random = new Random();
                ;//每隔一秒推送一次
                clients.forEach((sessionId, client) -> {
                            client.sendEvent("pushpoint", new Point(random.nextInt(100), random.nextInt(100)));
                        }
                );
            }
        }, 1000, 1000);

        latch.await();
    }

}

Client

<!DOCTYPE html>
<html>
<head>
    <title>netty-socketio测试</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <script src="socket.io.js"></script>
    <script src="jquery-1.7.2.min.js"></script>
    <script>
        $(function () {
            socket = io.connect('http://localhost:12121');
            socket.on('connect', function (e) {
                var session = socket.id;
                socket.on("result", function (data) {
                    var eq = data.sessionId === session;
                    debugger;
                });
            })
        });

    </script>
</head>

<body>

<div id="display" style="height:50px;background-color:grey;">
    x=<span id="x">0</span>, y=<span id="y">0</span>
</div>

</body>

</html>

Guess you like

Origin blog.csdn.net/qq_28822933/article/details/85627541