Maven_Netty5 实例

这里写图片描述

netty-client

HeartBeatReqHandler.java

package com.demo.netty.client;

import java.util.concurrent.TimeUnit;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class HeartBeatReqHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("heart")) {
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("HeartBeatReqHandler: " + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("pipe1_client $_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 90000, TimeUnit.MILLISECONDS);
    }

    private class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(final ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        public void run() {
            ctx.writeAndFlush(Unpooled.copiedBuffer("heartBeat$_".getBytes()));
        }

    }

}

NettyClient.java

package com.demo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;

public class NettyClient {

    public static Channel ch;
    private String host;
    private int port;

    public NettyClient(String host, int port) {
        super();
        this.host = host;
        this.port = port;
    }

    public void start() {
        try {
            new Thread(new NettyRunnable()).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class NettyRunnable implements Runnable {

        public void run() {

            while (true) {
                System.out.println("启动线程,连接" + host + ":" + port);
                try {
                    NettyClient.connect(host, port);
                } catch (Exception e) {
                    try {
                        Thread.sleep(6000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    public static synchronized void connect(String host, int port) throws Exception {
        if (host == null || port < 0) {
            throw new NullPointerException("socket unconnected");
        }

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 6000).handler(new ClientChildChannelHandler());

            ch = b.connect(host, port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("................断开连接................");

        } finally {
            group.shutdownGracefully();
        }
    }

    private static class ClientChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {

            // 使用长度依赖的话需要在数据包前声明数据包的长度
            // ch.pipeline().addLast("lengthField",
            // new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
            // 换行分割
            // ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
            // ch.pipeline().addLast(new StringDecoder());

            // 自定义分割符
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$_".getBytes())));
            ch.pipeline().addLast(new StringDecoder());

            ch.pipeline().addLast(new ReadTimeoutHandler(300));
            ch.pipeline().addLast(new HeartBeatReqHandler());

            ch.pipeline().addLast(new Pipe1ClientHandler());
            ch.pipeline().addLast(new Pipe2ClientHandler());
        }

    }

    public static void main(String[] args) {
        new NettyClient("127.0.0.1", 55025).start();
    }

}

Pipe1ClientHandler.java

package com.demo.netty.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class Pipe1ClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("pipe1")) {
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("Pipe1ClientHandler: " + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("pipe2_client $_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

Pipe2ClientHandler.java

package com.demo.netty.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class Pipe2ClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("pipe2")) {
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("Pipe2ClientHandler: " + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("pipe3_server $_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

pom.xml

<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>
    <groupId>com.demo</groupId>
    <artifactId>netty-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

netty-client 实例源码

netty-server

HeartBeatResHandler.java

package com.demo.netty.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class HeartBeatResHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("heart")) {
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("HeartBeatResHandler:" + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("heartBeat$_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

NettyServer.java

package com.demo.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;

public class NettyServer {

    public void bind(int port) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ServerChildChannelHandler());

            ChannelFuture f = b.bind(port).sync();
            System.out.println("NettyServer:"+ port);

            f.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ServerChildChannelHandler extends ChannelInitializer<SocketChannel> {

        protected void initChannel(SocketChannel ch) throws Exception {

            // 使用长度依赖的话需要在数据包前声明数据包的长度
            // ch.pipeline().addLast("lengthField",
            // new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
            // 换行分割
            // ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
            // ch.pipeline().addLast(new StringDecoder());

            // 自定义分割符
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$_".getBytes())));
            ch.pipeline().addLast(new StringDecoder());

            ch.pipeline().addLast(new ReadTimeoutHandler(300));
            ch.pipeline().addLast(new HeartBeatResHandler());

            ch.pipeline().addLast(new Pipe1ServerHandler());
            ch.pipeline().addLast(new Pipe2ServerHandler());

        }
    }

    public static void main(String[] args) throws Exception {
        new NettyServer().bind(55025);
    }
}

Pipe1ServerHandler.java

package com.demo.netty.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class Pipe1ServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("pipe1")) {
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("Pipe1ServerHandler: " + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("pipe1_server $_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

Pipe2ServerHandler.java

package com.demo.netty.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class Pipe2ServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = (String) msg;

            if (!message.contains("pipe2")) {
                System.out.println("fireChannelRead:" + message);
                ctx.fireChannelRead(msg);
                return;
            }

            System.out.println("Pipe2ServerHandler: " + message);
            ctx.writeAndFlush(Unpooled.copiedBuffer("pipe2_server $_".getBytes()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

pom.xml

<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>
    <groupId>com.demo</groupId>
    <artifactId>netty-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

netty-server 实例源码


https://blog.csdn.net/u010853261/article/details/55803933

好的,让我来为您解答这个问题。 首先,需要明确的是,JDK17和Netty是Java开发中非常常用的工具和框架,而Spring Boot是一个基于Spring框架的快速开发工具,可以帮助我们快速搭建Java Web应用程序。 接下来,我将为您提供一个使用JDK17、Netty和Spring Boot搭建IoT项目的简单实例: 1. 确保您已经安装好了JDK17,并且已经配置好了环境变量。 2. 创建一个Spring Boot项目,可以使用工具如IntelliJ IDEA或Eclipse。在创建项目时,选择Maven或Gradle构建工具。 3. 在项目中添加Netty依赖,可以在pom.xml或build.gradle文件中添加以下依赖: ``` <!-- Maven --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.43.Final</version> </dependency> // Gradle compile group: 'io.netty', name: 'netty-all', version: '4.1.43.Final' ``` 4. 创建IoT服务类,例如MyIoTServer: ``` @Component public class MyIoTServer { @Value("${netty.port}") private int port; public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new MyIoTServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 5. 创建IoT服务处理器类,例如MyIoTServerHandler: ``` @Component public class MyIoTServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理接收到的消息 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 处理异常 } } ``` 6. 在application.properties或application.yml文件中配置Netty端口号: ``` # application.properties netty.port=8080 # application.yml netty: port: 8080 ``` 7. 在启动类中启动IoT服务: ``` @SpringBootApplication public class MyApplication { public static void main(String[] args) throws InterruptedException { ApplicationContext context = SpringApplication.run(MyApplication.class, args); MyIoTServer myIoTServer = context.getBean(MyIoTServer.class); myIoTServer.start(); } } ``` 以上就是一个使用JDK17、Netty和Spring Boot搭建IoT项目的简单实例。当然,这只是一个初步的示例,实际开发中还需要根据具体需求进行相关的配置和开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值