vertx编写socket

该文展示了如何在Java环境中利用Vert.x框架创建WebSocket服务器,结合SpringBoot进行应用集成,实现客户端与服务器之间的消息交互。通过引入相关依赖,如Redis用于扩展功能,以及Guava、Lombok和Hutool等工具库,构建了一个简单的WebSocket服务,能够接收和响应客户端消息,并能定期推送消息给所有连接的客户端。
摘要由CSDN通过智能技术生成

参考信息
Vert.x Socket推送消息

导入依赖

<!--   vertx tcp开发依赖     -->
<dependency>
   <groupId>io.vertx</groupId>
   <artifactId>vertx-core</artifactId>
   <version>4.3.1</version>
</dependency>


<!--   spring boot 依赖   -->
 <dependency>
<groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


 <!--   其他工具类依赖     -->

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>31.1-jre</version>
</dependency>


<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
</dependency>


<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.8.11</version>
</dependency>




<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.8.graal</version>
</dependency>

<dependency>
  <groupId>com.alibaba.fastjson2</groupId>
  <artifactId>fastjson2</artifactId>
  <version>2.0.25</version>
</dependency>

编写 socket服务

这里使用 main 方法直接启动,如果整合 spring boot 可以使用 ApplicationRunner 整合

package com.example.socketdemo.socket;

import com.google.common.collect.Maps;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.ServerWebSocket;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
public class VertxSocketServer extends AbstractVerticle {


    private final static Map<String, ServerWebSocket> LOCAL_MAP = Maps.newHashMap();

    @Override
    public void start() throws Exception {
        vertx.createHttpServer().webSocketHandler(serverWebSocket -> {
            String path = serverWebSocket.path();
            String id = serverWebSocket.textHandlerID();
            if (path.equals("/myapp")) {
                serverWebSocket.handler(buffer -> {
                    LOCAL_MAP.put(id, serverWebSocket);
                    System.out.println("--------------------");
                    System.out.println("server收到消息: " + buffer.toString());
                    System.out.println("--------------------");
                    serverWebSocket.writeTextMessage("我是服务器,我收到你的消息了 " + LocalDateTime.now());
                });
            } else {
                serverWebSocket.reject(); // 拒绝连接
            }

            serverWebSocket.closeHandler(res -> {
                log.info("socket 断开连接==== {}", id);
                LOCAL_MAP.remove(id);
            });


        }).listen(9099, server -> {
            if (server.succeeded()) {
                System.out.println("启动成功");
            } else {
                server.cause().printStackTrace();
            }
        });


        // 模拟全局推送消息 30秒后
        vertx.setPeriodic(10000, timer -> {
            System.out.println("时间到了, map size " + LOCAL_MAP.size());
            LOCAL_MAP.forEach((k, v) -> {
                System.out.println("定时任务触发");
                System.out.println("id: " + k);
                v.writeTextMessage("我是服务器,这是定时任务发送的消息 " + LocalDateTime.now());
//                v.close(); // 自己决定什么时候关闭
            });
        });

    }


    public static void send(String message) {
        LOCAL_MAP.forEach((k, v) -> {
            System.out.println("定时任务触发");
            System.out.println("id: " + k);
            v.writeTextMessage(message + LocalDateTime.now());
//            v.close(); // 自己决定什么时候关闭
        });
    }

    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxSocketServer());
    }
}


ApplicationRunner 启动

@Component
public class ThreadApplicationRuner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Vertx.vertx().deployVerticle(new VertxTCP2Server());
    }
}

Html测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:9099/myapp");
        socket.onmessage = function (event) {
            alert("data from websocket: " + event.data);
        };
        socket.onopen = function (event) {
            alert("Web Socket 打开!");
        };
        socket.onclose = function (event) {
            console.log("Web Socket 关闭.");
        };
    } else {
        alert("Your browser does not support Websockets. (Use Chrome)");
    }
 
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("The socket is not open.");
        }
    }
</script>
<form onsubmit="return false;">
    <input type="text" name="message" value="Hello, World!"/>
    <input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)"/>
</form>
</body>
</html>
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值