Netty4具体解释二:开发第一个Netty应用程序
既然是入门,那我们就在这里写一个简单的Demo,client发送一个字符串到server端,server端接收字符串后再发送回client。
2.1、配置开发环境
- Client连接到Server端
- 建立链接发送/接收数据
- Server端处理全部Client请求
- BootsTrapping:配置server端基本信息
- ServerHandler:真正的业务逻辑处理
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();
}
}
}
2. 创建一个EventLoopGroup来处理各种事件,如处理链接请求,发送接收数据等。
3. 定义本地InetSocketAddress( port)好让Server绑定
4. 创建childHandler来处理每个链接请求
5. 全部准备好之后调用ServerBootstrap.bind()方法绑定Server
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
}
}
我们在上面程序中也重写了exceptionCaught方法,这里就是对当异常出现时的处理。
- 连接到Server
- 向Server写数据
- 等待Server返回数据
- 关闭连接
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好让client连接
4. 当连接完毕之后,Handler会被运行一次
5. 全部准备好之后调用ServerBootstrap.connect()方法连接Server
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> {
/**
*此方法会在连接到server后被调用
* */
public void channelActive(ChannelHandlerContext ctx) {
ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
}
/**
*此方法会在接收到server数据后调用
* */
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()方法,此方法接收到的可能是一些数据片段,比方server发送了5个字节数据,Client端不能保证一次所有收到,比方第一次收到3个字节,第二次收到2个字节。我们可能还会关心收到这些片段的顺序是否可发送顺序一致,这要看详细是什么协议,比方基于TCP协议的字节流是能保证顺序的。
Netty4具体解释二:开发第一个Netty应用程序的更多相关文章
- Netty入门二:开发第一个Netty应用程序
Netty入门二:开发第一个Netty应用程序 时间 2014-05-07 18:25:43 CSDN博客 原文 http://blog.csdn.net/suifeng3051/article/ ...
- Netty实战二之自己的Netty应用程序
接下来我们将展示如何构建一个基于Netty的客户端和服务器,程序很简单:客户端将消息发送给服务器,而服务器再将消息回送给客户端,这将是一个对你而言很重要的第一个netty的实践经验. 1.设置开发环境 ...
- 用Qt开发第一个Hello World程序
配置好Qt的环境变量之后,我们才可以进行下面的通过终端来使用Qt开发这个第一个程序 因为Qt的文件路径不能有中文否则会报错,所以一般都把工程文件都建立在根目录 我们创建的Qt程序包含两个部分:1.GU ...
- Xamarin开发的一个简单画图程序分享
最近Xamarin比较火,于是稍微看了下,感觉接触过MVC的都应该能很快上手,还挺有意思,于是忍不住写了个简单的画图程序,之前看帖子有人说装不上或者无法部署,估计我比较幸运,编译完了一次就安装成功了, ...
- iphone开发第一个UI应用程序QQ
#import <UIKit/UIKit.h> @interface HViewController : UIViewController @property (retain, nonat ...
- Netty4具体解释三:Netty架构设计
读完这一章,我们基本上能够了解到Netty全部重要的组件,对Netty有一个全面的认识.这对下一步深入学习Netty是十分重要的,而学完这一章.我们事实上已经能够用Netty解决一些常规的问 ...
- Java程序员从笨鸟到菜鸟之(五十一)细谈Hibernate(二)开发第一个hibernate基本详解
在上篇博客中,我们介绍了<hibernate基本概念和体系结构>,也对hibernate框架有了一个初步的了解,本文我将向大家简单介绍Hibernate的核心API调用库,并讲解一下它的基 ...
- 【原创】高性能网络编程(二):上一个10年,著名的C10K并发连接问题
1.前言 对于高性能即时通讯技术(或者说互联网编程)比较关注的开发者,对C10K问题(即单机1万个并发连接问题)应该都有所了解."C10K"概念最早由Dan Kegel发布于其个人 ...
- 李洪强iOS开发之【零基础学习iOS开发】【02-C语言】02-第一个C语言程序
前言 前面已经唠叨了这么多理论知识,从这讲开始,就要通过接触代码来学习C语言的语法.学习任何一门语言,首先要掌握的肯定是语法.学习C语言语法的目的:就是能够利用C语言编写程序,然后运行程序跟硬件(计算 ...
随机推荐
- gocode 安装
1.安装git,将git/bin添加至PATH 2.执行go get -u github.com/nsf/gocode 3.在%GOPATH%/bin/下会生成gocode.exe
- 通过Servlet的response绘制页面验证码
java部分 package com.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; ...
- 2的N次方
/**编程精确计算2的N次方.(N是介于100和1000之间的整数)*//*问题代码:#include<stdio.h>#include<math.h>int main(){ ...
- Apriori算法在购物篮分析中的运用
购物篮分析是一个很经典的数据挖掘案例,运用到了Apriori算法.下面从网上下载的一超市某月份的数据库,利用Apriori算法进行管理分析.例子使用Python+MongoDB 处理过程1 数据建模( ...
- 10055 - Hashmat the Brave Warrior
Problem A Hashmat the brave warrior Input: standard input Output: standard output Hashmat is a brave ...
- seajs配合spm应用之四弹出框
前面描述了 seajs的弹出遮罩层, 还没讲到弹出框, 这里接着把那几个例子介绍完. 目前已经有的工作是, 点击toggle按钮,可以弹出一个背投一样的暗灰色遮罩层, 主要的作用就是遮住当前页面上所有 ...
- bzoj 2209: [Jsoi2011]括号序列 splay
2209: [Jsoi2011]括号序列 Time Limit: 20 Sec Memory Limit: 259 MBSubmit: 833 Solved: 392[Submit][Status ...
- bzoj 2705: [SDOI2012]Longge的问题 歐拉函數
2705: [SDOI2012]Longge的问题 Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 1035 Solved: 669[Submit][S ...
- Count The Pairs
hdu4750:http://acm.hdu.edu.cn/showproblem.php?pid=4750 题意:给你一个带权无向图,然后让你求这样的点对s,t,使得s--t的所有路径上的最大的边的 ...
- h.264并行解码算法分析
并行算法类型可以分为两类 Function-level Decomposition,按照功能模块进行并行 Data-level Decomposition,按照数据划分进行并行 Function-le ...