springboot创建TCP服务端与TCP客户端

文章目录

概要

        使用springboot创建一个TCP服务端与TCP客户端

流程

TCP服务端

服务端ip是采取的本机ip,port可以自定义设置

例如本机ip:192.168.1.100:5201

创建流程

使用hutool工具

文档地址:NIO封装-NioServer和NioClient (hutool.cn)

导入hutool依赖后,进行tcp服务端的创建

 

static HashMap<String, NioServer> tcpServerMap = new HashMap<>();

 public void init(Integer port) {
        try {
            if (!tcpServerMap.containsKey(String.valueOf(port))) {
                NioServer server = new NioServer(port);
                tcpServerMap.put(String.valueOf(port), server);
                server.setChannelHandler((sc) -> {
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    try {
                        //从channel读数据到缓冲区
                        int readBytes = sc.read(readBuffer);
                        if (readBytes > 0) {
                            //Flips this buffer.  The limit is set to the current position and then
                            // the position is set to zero,就是表示要从起始位置开始读取数据
                            readBuffer.flip();
                            //eturns the number of elements between the current position and the  limit.
                            // 要读取的字节长度
                            byte[] bytes = new byte[readBuffer.remaining()];
                            //将缓冲区的数据读到bytes数组
                            readBuffer.get(bytes);
                            String body = StrUtil.utf8Str(bytes);
                            log.info("[{}]: {}", sc.getRemoteAddress(), body);
                            // 回写
                            doWrite(sc, body);
                        } else if (readBytes < 0) {
                            IoUtil.close(sc);
                        }
                    } catch (IOException e) {
                        log.error("读取服务器消息失败! -------> ", e);
                    }
                });
                server.listen();
            }

        } catch (Exception e) {
            log.error("初始化失败,{}", e.getMessage(), e);
        }

    }

服务端监听数据

public void doWrite(SocketChannel channel, String response) throws IOException {
        log.info("收到服务监听到的消息 -----> {}", response);

        JSONObject jsonObject = JSONObject.parseObject(response);
        log.info("服务器监听到的消息转为json -----> {}", jsonObject);

        //将缓冲数据写入渠道,返回给客户端
        channel.write(BufferUtil.createUtf8("数据"));
}

TCP客户端

通过ip,port来创建,采用TCP长连接

 

    static HashMap<String, NioClient> tcpClientMap = new HashMap<>();

public void init(Integer port, String ip) {
        try {
            if (!tcpClientMap.containsKey(ip)) {
                NioClient client = new NioClient(ip, port);
                tcpClientMap.put(ip, client);

                // 创建TCP服务后发送登录验证消息
                String msg = getLoginString();
                if (msg == null || msg.isEmpty()) {
                    log.info("获取登录信息失败-----> msg为null 或者 \"\"");
                } else {
                    log.info("登录string-----> {}", msg);
                    byte[] bytes = msg.getBytes();
                    log.info("登录string 字节数组-----> {}", msg.getBytes());
                    client.write(ByteBuffer.wrap(bytes));
                }

                // 开始监听TCP消息
                client.setChannelHandler((sc) -> {
                    try {
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        int readBytes = sc.read(readBuffer);
                        if (readBytes > 0) {
                            readBuffer.flip();
                            byte[] bytes = new byte[readBuffer.remaining()];
                            readBuffer.get(bytes);

                            String body = StrUtil.utf8Str(bytes);

                            log.info("TCP监听的消息----》[{}]: {}", sc.getRemoteAddress(), body);

                        

                        } else if (readBytes < 0) {
//                        sc.close();
                        }
                    } catch (Exception e) {
                        log.error("异常----》{}", e.getMessage(), e);
                    }
                });
                client.listen();
            }
        } catch (Exception e) {
            log.error("启动TCP服务失败!", e);
        }
    }
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中使用Netty连接多个TCP服务端可以通过以下步骤实现: 1. 首先,确保你已经在Spring Boot项目中引入了Netty的依赖。可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency> ``` 2. 创建一个Netty客户端的处理器类,用于处理接收到的消息。可以继承`SimpleChannelInboundHandler`类,并重写`channelRead0`方法来处理接收到的消息。 ```java public class NettyClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // 处理接收到的消息 System.out.println("Received message: " + msg); } } ``` 3. 创建一个Netty客户端的启动类,用于配置和启动Netty客户端。 ```java @Configuration public class NettyClientConfig { @Value("${netty.server.host}") private String serverHost; @Value("${netty.server.port}") private int serverPort; @Bean public EventLoopGroup eventLoopGroup() { return new NioEventLoopGroup(); } @Bean public Bootstrap bootstrap(EventLoopGroup eventLoopGroup, NettyClientHandler nettyClientHandler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringEncoder()); pipeline.addLast(new StringDecoder()); pipeline.addLast(nettyClientHandler); } }); return bootstrap; } @Bean public ChannelFuture channelFuture(Bootstrap bootstrap) throws InterruptedException { return bootstrap.connect(serverHost, serverPort).sync(); } } ``` 4. 在配置文件中配置要连接的多个TCP服务端的主机和端口。 ```properties # application.properties netty.server.host=127.0.0.1 netty.server.port=8080 ``` 5. 在需要使用Netty客户端的地方注入`ChannelFuture`对象,并使用它来发送消息给服务端。 ```java @Service public class NettyClientService { @Autowired private ChannelFuture channelFuture; public void sendMessage(String message) { if (channelFuture.channel().isActive()) { channelFuture.channel().writeAndFlush(message); } else { // 连接未建立或已断开,处理相应逻辑 } } } ``` 这样,你就可以在Spring Boot项目中使用Netty连接多个TCP服务端了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值