Netty-SocketIO(SpringBoot版本SocketIO)

509 阅读1分钟

注意版本!!!

注意版本!!!

注意版本!!!

第一 看看SpringBoot版本

第二 看看Netty-SocketIO版本

第三 看看客户端版本

我的Netty-SocketIO是1.7.18,SpringBoot是2.X,客户端版本是v2

第一步,搭建服务

package org.doc.learn.Server;

import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class SocketServer implements CommandLineRunner {

    @Autowired
    private SocketIOServer socketIOServer;

    @Override
    public void run(String... args) throws Exception {
        socketIOServer.start();
    }
}

第二步,配置文件

package org.doc.learn.common.config;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;


@SpringBootConfiguration
public class SocketConfig {

    @Bean
    public SocketIOServer socketIOServer(){
        Configuration config = new Configuration();
        config.setHostname("127.0.0.1");
        config.setPort(8200);
        config.setPingTimeout(3000);
        config.setPingInterval(6000);
        config.getSocketConfig().setTcpKeepAlive(true);
        config.setBossThreads(1);
        config.setWorkerThreads(200);
        config.setAllowCustomRequests(true);
        return new SocketIOServer(config);
    }


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

}

第三步,设置事件

package org.doc.learn.controller;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SocketIOEventHandler {

    @Autowired
    private SocketIOServer server;

    @OnConnect
    public void onConnect(SocketIOClient client) {
        System.out.println("Connected to server: " + client.getSessionId());
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("Disconnected from server: "+client.getSessionId());
    }

    @OnEvent("message")
    public void onMessage(SocketIOClient client, String message) {
        System.out.println("Message received: " + message);

    }
}

第四步,发送请求(默认Contet-Type:Application/json)

1-22.png