Netty入门二:开发第一个Netty应用程序

时间 2014-05-07 18:25:43  CSDN博客
主题 Netty

既然是入门,那我们就在这里写一个简单的Demo,客户端发送一个字符串到服务器端,服务器端接收字符串后再发送回客户端。

2.1、配置开发环境

1.安装JDK

2.去官网下载jar包

(或者通过pom构建)

2.2、认识下Netty的Client和Server

一个Netty应用模型,如下图所示,但需要明白一点的是,我们写的Server会自动处理多客户端请求,理论上讲,处理并发的能力决定于我们的系统配置及JDK的极限。

  1. Client连接到Server端
  2. 建立链接发送/接收数据
  3. Server端处理所有Client请求

这里有一个形象的比喻来形容Netty客户端和服务器端的交互模式,把你比作一个Client,把山比作一个Server,你走到山旁,就是和山建立了链接,你向山大喊了一声,就代表向山发送了数据,你的喊声经过山的反射形成了回声,这个回声就是服务器的响应数据。如果你可以离开,就代表断开了链接,当然你也可以再回来。一次可以后好多人向山大喊,他们的喊声也一定会得到山的回应。

2.3 写一个Netty Server

一个NettyServer程序主要由两部分组成:

  • BootsTrapping:配置服务器端基本信息
  • ServerHandler:真正的业务逻辑处理

2.3.1 BootsTrapping的过程:

package NettyDemo.echo.server;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import java.net.InetSocketAddress;
import NettyDemo.echo.handler.EchoServerHandler;
public class EchoServer {
private static final int port = 8080;
public void start() throws InterruptedException {
ServerBootstrap b = new ServerBootstrap();// 引导辅助程序
EventLoopGroup group = new NioEventLoopGroup();// 通过nio方式来接收连接和处理连接
try {
b.group(group);
b.channel(NioServerSocketChannel.class);// 设置nio类型的channel
b.localAddress(new InetSocketAddress(port));// 设置监听端口
b.childHandler(new ChannelInitializer<SocketChannel>() {//有连接到达时会创建一个channel
protected void initChannel(SocketChannel ch) throws Exception {
// pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务
ch.pipeline().addLast("myHandler", new EchoServerHandler());
}
});
ChannelFuture f = b.bind().sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully().sync();//关闭EventLoopGroup,释放掉所有资源包括创建的线程
}
}
public static void main(String[] args) {
try {
new EchoServer().start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

1. 创建一个ServerBootstrap实例 
     2. 创建一个EventLoopGroup来处理各种事件,如处理链接请求,发送接收数据等。 
     3. 定义本地InetSocketAddress( port)好让Server绑定 
     4. 创建childHandler来处理每一个链接请求    
     5. 所有准备好之后调用ServerBootstrap.bind()方法绑定Server

2.3.2 业务逻辑ServerHandler:

要想处理接收到的数据,我们必须继承ChannelInboundHandlerAdapter接口,重写里面的MessageReceive方法,每当有数据到达,此方法就会被调用(一般是Byte类型数组),我们就在这里写我们的业务逻辑:

package NettyDemo.echo.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
/**
* Sharable表示此对象在channel间共享
* handler类是我们的具体业务类
* */
@Sharable//注解@Sharable可以让它在channels间共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("server received data :" + msg);
ctx.write(msg);//写回数据,
}
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有写回的数据
.addListener(ChannelFutureListener.CLOSE); //当flush完成后关闭channel
}
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
cause.printStackTrace();//捕捉异常信息
ctx.close();//出现异常时关闭channel
}
}

2.3.3关于异常处理:

我们在上面程序中也重写了exceptionCaught方法,这里就是对当异常出现时的处理。

 

2.4 写一个Netty Client

 

一般一个简单的Client会扮演如下角色:

  1. 连接到Server
  2. 向Server写数据
  3. 等待Server返回数据
  4. 关闭连接

4.4.1  BootsTrapping的过程:

 

和Server端类似,只不过Client端要同时指定连接主机的IP和Port。

package NettyDemo.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
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; import NettyDemo.echo.handler.EchoClientHandler; 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 Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class);
b.remoteAddress(new InetSocketAddress(host, port));
b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception {
if(future.isSuccess()){
System.out.println("client connected");
}else{
System.out.println("server attemp failed");
future.cause().printStackTrace();
} }
});
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
} public static void main(String[] args) throws Exception { new EchoClient("127.0.0.1", 3331).start();
}
}

1. 创建一个ServerBootstrap实例 
     2. 创建一个EventLoopGroup来处理各种事件,如处理链接请求,发送接收数据等。 
     3. 定义一个远程InetSocketAddress好让客户端连接 
     4. 当连接完成之后,Handler会被执行一次    
     5. 所有准备好之后调用ServerBootstrap.connect()方法连接Server

4.4.2 业务逻辑ClientHandler:

 

我们同样继承一个SimpleChannelInboundHandler来实现我们的Client,我们需要重写其中的三个方法:

package NettyDemo.echo.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.util.CharsetUtil; @Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
/**
*此方法会在连接到服务器后被调用
* */
public void channelActive(ChannelHandlerContext ctx) {
ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
}
/**
*此方法会在接收到服务器数据后调用
* */
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
System.out.println("Client received: " + ByteBufUtil.hexDump(in.readBytes(in.readableBytes())));
}
/**
*捕捉到异常
* */
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
} }

其中需要注意的是 channelRead0()方法,此方法接收到的可能是一些数据片段,比如服务器发送了5个字节数据,Client端不能保证一次全部收到,比如第一次收到3个字节,第二次收到2个字节。我们可能还会关心收到这些片段的顺序是否可发送顺序一致,这要看具体是什么协议,比如基于TCP协议的字节流是能保证顺序的。

还有一点,在Client端我们的业务Handler继承的是SimpleChannelInboundHandler,而在服务器端继承的是ChannelInboundHandlerAdapter,那么这两个有什么区别呢?最主要的区别就是SimpleChannelInboundHandler在接收到数据后会自动release掉数据占用的Bytebuffer资源(自动调用Bytebuffer.release())。而为何服务器端不能用呢,因为我们想让服务器把客户端请求的数据发送回去,而服务器端有可能在channelRead方法返回前还没有写完数据,因此不能让它自动release。

Netty入门二:开发第一个Netty应用程序的更多相关文章

  1. Netty4具体解释二:开发第一个Netty应用程序

        既然是入门,那我们就在这里写一个简单的Demo,client发送一个字符串到server端,server端接收字符串后再发送回client. 2.1.配置开发环境 1.安装JDK 2.去官网下 ...

  2. Netty实战二之自己的Netty应用程序

    接下来我们将展示如何构建一个基于Netty的客户端和服务器,程序很简单:客户端将消息发送给服务器,而服务器再将消息回送给客户端,这将是一个对你而言很重要的第一个netty的实践经验. 1.设置开发环境 ...

  3. C语言入门:02.第一个C语言程序

    一.开发工具的选择(1)可以用来写代码的工具:记事本.UltraEdit.Vim.Xcode等(2)选择Xcode的原因:苹果官方提供的开发利器.简化开发过程.有高亮显示功能 (3)使用Xcode新建 ...

  4. ASP.NET MVC3入门教程之第一个WEB应用程序

    本文转载自:http://www.youarebug.com/forum.php?mod=viewthread&tid=91&extra=page%3D1 上一节,我们已经搭建好了AS ...

  5. netty 入门二 (传输bytebuf 或者pojo)

    基于流的数据传输:在基于流的传输(如TCP / IP)中,接收的数据被存储到套接字接收缓冲器中. 不幸的是,基于流的传输的缓冲区不是数据包的队列,而是字节队列. 这意味着,即使您将两个消息作为两个独立 ...

  6. Netty入门(八)构建Netty HTTP/HTTPS应用

    HTTP/HTTPS 是最常见的一种协议,这节主要是看一下 Netty 提供的 ChannelHaandler. 一.HTTP Decoder,Encoder 和 Codec HTTP 是请求-响应模 ...

  7. 用Qt开发第一个Hello World程序

    配置好Qt的环境变量之后,我们才可以进行下面的通过终端来使用Qt开发这个第一个程序 因为Qt的文件路径不能有中文否则会报错,所以一般都把工程文件都建立在根目录 我们创建的Qt程序包含两个部分:1.GU ...

  8. Xamarin开发的一个简单画图程序分享

    最近Xamarin比较火,于是稍微看了下,感觉接触过MVC的都应该能很快上手,还挺有意思,于是忍不住写了个简单的画图程序,之前看帖子有人说装不上或者无法部署,估计我比较幸运,编译完了一次就安装成功了, ...

  9. iphone开发第一个UI应用程序QQ

    #import <UIKit/UIKit.h> @interface HViewController : UIViewController @property (retain, nonat ...

随机推荐

  1. 简单说说什么是Restful

    在确定要把自己的服务创建成RESTFUL之前,要明白什么样的服务什么是RESTFUL service(https://en.wikipedia.org/wiki/Representational_st ...

  2. Photon——Feature Overview 功能概述

    Photon——Feature Overview 功能概述   Feature Overview 功能概述        Photon is a real-time socket server and ...

  3. iOS - 正则表达式判断邮箱、身份证,车牌,URL等..是否正确:

    //邮箱 + (BOOL) validateEmail:(NSString *)email { NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Z ...

  4. iot_programe Makefile hacking

    /***************************************************************************** * iot_programe Makefi ...

  5. HDU5880 Family View ac自动机第二题

    Steam is a digital distribution platform developed by Valve Corporation offering digital rights mana ...

  6. VC中键盘键的对应关系

    转载:VC中如何响应键盘和鼠标事件 VC 中用 KeyPress 表示键盘响应的所有事件,包括 OnKeyDown 事件(键按下). OnKeyUp 事件(键按下后弹起)和 OnKeyPress 事件 ...

  7. 《selenium2 python 自动化测试实战》(16)——js操作补充

    js修改readonly属性 我们看到这里日期框标签中有readonly属性,如果我们直接send_keys就无法输入内容,这时我们需要先去掉readonly属性: js ='document.get ...

  8. 船长带你看书——《selenium2 python 自动化测试实战》(1)

    有很多selenium的教程,你没有从头看,当你看的时候已经很难跟上作者的节奏了.现在,你有机会再从头学一次了.从今天开始,船长会从最基本的知识开始,和大家一起学selenium.能不能跟着一起就看大 ...

  9. [BZOJ5329][SDOI2018]战略游戏

    bzoj luogu Description 省选临近,放飞自我的小Q无心刷题,于是怂恿小C和他一起颓废,玩起了一款战略游戏. 这款战略游戏的地图由n个城市以及m条连接这些城市的双向道路构成,并且从任 ...

  10. MYSQL子查询例题以及答案

    More Subqueries Quizzes Above is the ERD for the database again - it might come in handy as you tack ...