`
chaijuntao
  • 浏览: 24761 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

netty学习【一】:发送字符串

 
阅读更多

1、简介

Netty是基于Java NIO的网络应用框架.
Netty是一个NIO client-server(客户端服务器)框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议。Netty提供了一种新的方式来使开发网络应用程序,这种新的方式使得它很容易使用和有很强的扩展性。Netty的内部实现时很复杂的,但是Netty提供了简单易用的api从网络处理代码中解耦业务逻辑。Netty是完全基于NIO实现的,所以整个Netty都是异步的。
网络应用程序通常需要有较高的可扩展性,无论是Netty还是其他的基于Java NIO的框架,都会提供可扩展性的解决方案。Netty中一个关键组成部分是它的异步特性.

2、demo实例

2.1、pom文件

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>tj.cmcc.org</groupId>
  <artifactId>netty.rpc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>netty.rpc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.6.Final</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>netty.rpc</finalName>
  </build>
</project>

 

2.2、服务器端

EchoServer.java

package hello_netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
 * 服务端启动类
 * • 配置服务器功能,如线程、端口
 * • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么
 * Created by tianjun on 2016/12/19 0019.
 */
public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception{

        EventLoopGroup eventLoopGroup = null;
        try {
            //创建ServerBootstrap实例来引导绑定和启动服务器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //创建NioEventLoopGroup对象来处理事件,如接受新连接、接收数据、写数据等等
            eventLoopGroup = new NioEventLoopGroup();
            //指定通道类型为NioServerSocketChannel,设置InetSocketAddress让服务器监听某个端口已等待客户端连接。
            final ServerBootstrap serverBootstrap1 = serverBootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                    .localAddress("localhost", port).childHandler(new ChannelInitializer<Channel>() {
                        //设置childHandler执行所有的连接请求
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            // 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            System.out.println("开始监听,端口为:"+channelFuture.channel().localAddress());
            channelFuture.channel().closeFuture().sync();
        }finally {
            eventLoopGroup.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) throws Exception {
        new EchoServer(20000).start();
    }
}

 EchoServerHandler.java

package hello_netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 服务端回调方法
 * Created by tianjun on 2016/12/19 0019.
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws UnsupportedEncodingException {
        System.out.println("server 读取数据……");
        //读取数据
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("接收客户端数据:" + body);
        //向客户端写数据
        System.out.println("server向client发送数据");
        String currentTime = new Date(System.currentTimeMillis()).toString();
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        System.out.println("server 读取数据完毕..");
        ctx.flush();//刷新后才将数据发出到SocketChannel

    }

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

    }
}

 

2.3、客户端

EchoClient.java

package hello_netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;

/**
 * 客户端启动类
 *  • 连接服务器
 *  • 写数据到服务器
 *  • 等待接受服务器返回相同的数据
 *  • 关闭连接
 * Created by tianjun on 2016/12/19 0019.
 */
public class EchoClient {
    private final String host;
    private final int port;

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

    public void start() throws InterruptedException {
        EventLoopGroup nioEventLoopGroup = null;
        try {

            //创建Bootstrap对象用来引导启动客户端
            Bootstrap bootstrap = new Bootstrap();
            //创建EventLoopGroup对象并设置到Bootstrap中,EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据
            nioEventLoopGroup = new NioEventLoopGroup();
            //创建InetSocketAddress并设置到Bootstrap中,InetSocketAddress是指定连接的服务器地址
            bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        //添加一个ChannelHandler,客户端成功连接服务器后就会被执行
                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            // • 调用Bootstrap.connect()来连接服务器
            ChannelFuture f = bootstrap.connect().sync();
            // • 最后关闭EventLoopGroup来释放资源
            f.channel().closeFuture().sync();
        }finally {
            nioEventLoopGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient("localhost", 20000).start();
    }

}

 EchoClientHandler.java

package hello_netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 客户端回调方法
 * Created by tianjun on 2016/12/19 0019.
 */
public class EchoClientHandler extends SimpleChannelInboundHandler {

    //客户端连接服务器后被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接服务器,开始发送数据……");
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuf firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
        ctx.writeAndFlush(firstMessage);
    }

    //• 从服务器接收到数据后调用
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {

        System.out.println("client 读取server数据..");
        //服务端返回消息后
        ByteBuf buf = (ByteBuf) o;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("服务端数据为 :" + body);

    }

    //• 发生异常时被调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client exceptionCaught..");
        // 释放资源
        ctx.close();
    }

}

 

分享到:
评论

相关推荐

    netty-client:netty client学习

    例如,发送一个字符串消息: ```java Channel channel = future.channel(); channel.writeAndFlush("Hello, Server!"); ``` 最后,别忘了在适当的时候关闭资源,例如在连接关闭时: ```java channel.closeFuture...

    Netty实践学习案例

    2. **编解码器的使用**:示例可能涉及自定义编解码器,例如,将字符串或特定协议格式的数据转换为 ByteBuf,反之亦然。 3. **心跳机制**:在长连接中,心跳机制非常重要,以检测连接是否断开。示例可能包含如何实现...

    Netty 框架学习 —— 第一个 Netty 应用(csdn)————程序.pdf

    在本篇关于“Netty框架学习——第一个Netty应用”的文章中,我们将深入理解如何使用Netty构建一个简单的Echo服务器和客户端。Netty是一个高性能、异步事件驱动的网络应用程序框架,广泛应用于Java领域的服务器开发。...

    netty encode decode

    例如,你可以通过设置合适的字符集,将接收到的字节流转换为字符串,或将字符串编码为字节流进行发送。 在实际应用中,Netty 的编码器和解码器可以组合使用,形成一个管道(Pipeline),这个管道会按照预定义的顺序...

    netty对象传输gzipdemo

    在传统的HTTP或FTP等协议中,数据通常以字符串或二进制流的形式进行传输。然而,Netty允许开发者直接传输Java对象,这是通过序列化和反序列化机制实现的。Netty提供了`ObjectEncoder`和`ObjectDecoder`这两个编解码...

    netty案例.zip

    在案例中,可能包含一个简单的StringEncoder和StringDecoder,它们分别用于将字符串编码为ByteBuf和从ByteBuf解码为字符串。 5. **Pipeline(管道)**: Pipeline是Netty处理I/O事件的链式结构,每个...

    NettyDemo包含客户端服务端

    例如,可以使用 `StringEncoder` 和 `StringDecoder` 将字符串转换成字节缓冲区,以便在网络上传输。 4. **消息处理**: 客户端可以向服务端发送自定义的消息类型。这些消息通常通过继承 `MessageToByteMessageCodec...

    netty实现的聊天代码

    Netty 提供了多种编解码器,如 `StringDecoder` 和 `StringEncoder`,可以方便地将字符串数据转换成 ByteBuf(Netty 的字节缓冲区),反之亦然。在本示例中,可能已经使用了这些编解码器来处理消息。 为了实现实时...

    JWTTest_netty.netcore_jwt_

    JWT是一种轻量级的身份认证和授权机制,它通过将用户信息编码为一个字符串(称为JWT),然后在客户端和服务端之间传递,以验证用户身份。JWT包含了三个部分:Header(头部)、Payload(负载)和Signature(签名)。...

    Netty初始学习示例

    例如,`StringDecoder`和`StringEncoder`可以用于处理字符串数据。 6. **粘包与拆包问题**: 在网络通信中,由于数据包大小不固定,可能会出现粘包或拆包现象。Netty通过自定义的解码器如`...

    Netty入门教程文档

    这一类错误产生的原因是业务系统不够健全,在接收输入后没有进行判断直接写入后台数据库造成的,比如数值数据输成全角数字字符、字符串数据后面有一个回车操作、日期格式不正确、日期越界等。这一类数据也要分类,...

    Netty-入门Netty编码

    例如,TimeServer 和 TimeClient 可能会使用这些编解码器来解析时间戳字符串的边界。 标签提到的“源码”意味着深入理解 Netty,需要查看其源代码。Netty 的源代码清晰且注释丰富,对于学习和调试都非常有帮助。...

    服务端Netty搭建

    在"服务端Netty搭建"这个主题中,我们将深入探讨如何利用Netty来创建一个能够处理文件传输和JSON格式字符串交互的服务端。 首先,Netty的核心概念是基于Reactor模式,它允许服务端同时处理多个客户端连接,而无需为...

    netty实现简单的聊天

    对于聊天应用,我们可能需要自定义一个Decoder来处理消息的解码,如将字节流转为字符串或自定义的消息对象;同时,也需要一个Encoder来处理消息的编码,将字符串或消息对象转化为适合网络传输的格式。 在连接管理...

    零学习netty网络IO通讯开发

    Netty提供了一系列的编码器和解码器,如LengthFieldBasedFrameDecoder用于处理带有长度字段的数据包,StringDecoder和StringEncoder则用于字符串的编码和解码。 6. **实战应用** 通过本课程,你可以学习到如何...

    基于netty的长链硬件服务端部分源码

    为了控制硬件,我们可能需要构建特定的报文结构,根据硬件的协议规范,将其编码成十六进制字符串,然后通过Netty的编码器发送出去。 在实际项目中,我们还需要考虑连接管理,例如连接建立、心跳维持、异常处理和...

    netty实现websocket例子

    这个功能可以通过在WebSocketServerHandler的channelRead0()方法中解析接收到的WebSocket文本帧,然后创建一个新的TextWebSocketFrame,将服务器的时间转换为字符串并附带在帧上,最后通过writeAndFlush()发送给...

    自动netty笔记111

    这个“自动Netty笔记111”可能是某个开发者或学习者记录的一系列关于Netty学习过程中的关键点和理解。下面将详细阐述Netty的相关知识点。 1. **异步事件驱动模型**: Netty采用了非阻塞I/O模型,基于Java NIO(Non...

    hello netty代码练习

    你可以根据需求自定义编码解码器,例如,如果你的协议基于字符串,可以使用 StringDecoder 和 StringEncoder。 6. **业务逻辑处理**:在 `channelRead()` 方法中,你可以编写处理接收到的数据的代码。当需要发送...

    netty-code源码

    6. **编码和解码器**:Netty提供了多种编码器和解码器,如StringDecoder和StringEncoder,用于将字符串与字节流之间的转换,以及protobuf等复杂协议的编解码器。 7. **零拷贝(Zero-Copy)**:Netty通过Direct...

Global site tag (gtag.js) - Google Analytics