SpringBoot 集成Netty-SocketIO

 

om.xml

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

application.properties

socketio.host=localhost
socketio.port=5380

 NettySocketioConfig.java


import com.corundumstudio.socketio.SocketIOServer;
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;

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

    //netty-socketio服务器
    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname(host);
        config.setPort(port);

        SocketIOServer server = new SocketIOServer(config);
        return server;
    }

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

LoginHandler.java

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginHandler {
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();
//客户端连上socket服务器时执行此事件
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        if (userId != null) {
            clientMap.put(userId, client);
        }
    }
//客户端断开socket服务器时执行此事件

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        if (userId != null) {
            clientMap.remove(userId);
            client.disconnect();
        }
    }
//服务器向客户端发送事件
    public void pushMessage(String userId) {
        if (!StringUtils.isEmpty(userId)) {
            SocketIOClient client = clientMap.get(userId);
            if (client != null) {
                client.sendEvent("pushMsg", "hello-Rorschache");
            }
        }
    }
}

DemoApplication.java

@SpringBootApplication
public class DemoApplication  implements CommandLineRunner {
	@Autowired
	private SocketIOServer socketIOServer;
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

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

SocketController.java

import com.zsw.test.demo.service.LoginHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SocketController {

    @GetMapping("push")
    public void push() {
        LoginHandler loginHandler = new LoginHandler();
        loginHandler.pushMessage("7729");
    }
}

前端测试html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>NETTY SOCKET.IO DEMO</title>
    <base>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
    <style>
        body {
            padding: 20px;
        }
        #console {
            height: 450px;
            overflow: auto;
        }
        .username-msg {
            color: orange;
        }
        .connect-msg {
            color: green;
        }
        .disconnect-msg {
            color: red;
        }
    </style>
</head>

<body>
    <div id="console" class="well"></div>
</body>
<script type="text/javascript">
    var socket;
    connect();

    function connect() {
        var opts = {
            query: 'userId=7729'
        };
        socket = io.connect('http://localhost:5380', opts);
        socket.on('connect', function () {
            console.log("连接成功");
            serverOutput('<span class="connect-msg">连接成功</span>');
        });
        socket.on('pushMsg', function (data) {
            output('<span class="username-msg">' + data + ' </span>');
            console.log(data);
        });

        socket.on('disconnect', function () {
            serverOutput('<span class="disconnect-msg">' + '已下线! </span>');
        });
    }
    
    function output(message) {
        var element = $("<div>" + " " + message + "</div>");
        $('#console').prepend(element);
    }

    function serverOutput(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }
</script>
</html>

运行截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rorschach01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值