Netty-Socketio整合Spring Cloud Gateway

首先搭建一个Netty-Socketio服务器

基于SpringBoot添加以下依赖:

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

编写启动类:

@SpringBootApplication
@Order(1)
public class ChatApplication implements CommandLineRunner {
    private SocketIOServer server;
    public static void main(String[] args){
        SpringApplication.run(ChatApplication.class,args);
    }
    @Bean
    public SocketIOServer socketIOServer() {
        Configuration config = new Configuration();
        config.setPort(8083);	//Netty-Socketio服务器端口
        this.server = new SocketIOServer(config);
        return server;
    }

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

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

编写实体类:

public class MessageEntity {
    private String message;
    private String username;
    //...此处省略set和get方法
}

编写MessageEventHandler:


@Component
public class MessageEventHandler {
    public static SocketIOServer socketIoServer;
    private Map<UUID,String> clientMap = new ConcurrentHashMap<>(16);

    @Autowired
    public MessageEventHandler(SocketIOServer server) {
        MessageEventHandler.socketIoServer = server;
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        UUID socketSessionId = client.getSessionId();   //获取SessionId
        String ip = client.getRemoteAddress().toString();   //获取Ip
        clientMap.put(socketSessionId,ip);  //添加到客户端map
        client.sendEvent("getip",ip);   //发送客户端ip给前端

        //发送上线通知给所有用户
        clientMap.forEach((k,v)-> socketIoServer.getClient(k).sendEvent("refresh",clientMap.values()));
    }
    
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        UUID socketSessionId = client.getSessionId(); //获取SessionId
        String ip = client.getRemoteAddress().toString();   //获取Ip
        clientMap.remove(socketSessionId);  //从客户端map中移除

        //发送下线通知给所有用户
        clientMap.forEach((k,v)-> socketIoServer.getClient(k).sendEvent("refresh",clientMap.values()));
    }

    @OnEvent("message")
    public void message(SocketIOClient client, AckRequest request, MessageEntity message){
        message.setUsername(client.getRemoteAddress().toString());
        clientMap.forEach((k,v)-> socketIoServer.getClient(k).sendEvent("receiveMsg",message));
    }

编写前端页面:

<!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://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
   <style>
    body { 
        padding:20px;
    }
    #console {  
        overflow: auto; 
    }
</style>
</head>

<body>
    <div id="console">未连接</div><br/>
    ip:<div id="myip"></div>
    <br/>
    <div style="float: left;">
        <div style="width: 500px;height: 300px;border:1px solid black;overflow-y:auto;"><div id = "view"></div></div>
        <input type="text" id="message"/>
        <input type="submit" id="submit" onclick="send()"/>
        <button onclick="connect(this)">上线</button>
    </div>

    <div style="float: left;margin-left: 30px">在线用户:<br>
        <ul id="all_users">

        </ul>
    </div>
</body>
         
<script type="text/javascript">
    var socket;
    var ip = null;


    // 获取当前时间
    function NowTime() {
        var time=new Date();
        var year=time.getFullYear();//获取年
        var month=time.getMonth()+1;//或者月
        var day=time.getDate();//或者天
        var hour=time.getHours();//获取小时
        var minu =time.getMinutes();//获取分钟
        var second=time.getSeconds();//或者秒
        var data=year+"-";
        if(month<10){
            data+="0";
        }
        data+=month+"-";
        if(day<10){
            data+="0"
        }
        data+=day+" ";
        if(hour<10){
            data+="0"
        }
        data+=hour+":";
        if(minu<10){
            data+="0"
        }
        data+=minu+":";
        if(second<10){
            data+="0"
        }
        data+=second;
        return data;
    }
    function connect(btn) {
    //这里填写之前设置的Netty-Socketio服务器端口,整合网关后需要把这里的8083端口改成网关的端口
        socket =  io.connect('http://localhost:8083', {
            transports:['websocket']
        });
        socket.on('connect', function(data) {
            $('#console').text(NowTime() +"客户端连接到服务端");
        });
        socket.on('getip',function (data) {
            $('#myip').text(data);
            ip = data;
        });
        socket.on('receiveMsg', function(data) {
            var element = $("<p>"+data.username+":"+data.message+"</p>");
            $('#view').prepend(element);
        });
        socket.on('refresh', function(data) {
            $('#all_users').html("");
            for (var i = 0;i < data.length;i++){
                var element = $("<li>"+data[i]+"</li>");
                $('#all_users').append(element);
            }
        });
        $(btn).text("下线");
        $(btn).attr("onclick","disconnect(this)");
    }
    function disconnect(btn) {
        socket.disconnect();
        $('#console').text("未连接");
        $('#myip').text("");
        $("#all_users").html("");
        $(btn).text("上线");
        $(btn).attr("onclick","connect(this)");
    }
    function send() {
        socket.emit('message',{message:$("#message").val()});
    }
</script>
</html>

搭建一个简单的Spring Cloud Gateway项目

pom文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-cloud-gateway-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-gateway-example</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.youyuan.core.customer</groupId>
                <artifactId>log4j2</artifactId>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

编写启动类:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

application.yml文件内容:

spring:
  cloud:
    gateway:
      routes:
      - predicates:
        - Path=/socket.io/**
        uri: "http://localhost:8083/"
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值