java netty教程_Netty4.1初学者教程(HelloWorld教程)
Netty是基于JAVA NIO类库的异步通信框架,其特点是:异步非阻塞、基于事件驱动、高性能、高可靠性和高可定制性。
官网下载地址:http://netty.io/downloads.html
下面看HelloWorld代码,所需jar包: netty-all-4.1.0.CR3.jar
服务器端实现代码:package what21.netty.tcp;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
public class TcpServer {
// 循环事件处理组
static final EventLoopGroup bossGroup = new NioEventLoopGroup();
static final EventLoopGroup workerGroup = new NioEventLoopGroup();
/**
* 运行
*
* @param host
* @param port
*/
public static void run(String host,int port){
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup,workerGroup);
server.channel(NioServerSocketChannel.class);
server.childHandler(new ChannelInitializer() {
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder",
new LengthFieldPrepender(4));
pipeline.addLast("decoder",
new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder",
new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpServerHandler());
}
});
server.option(ChannelOption.SO_BACKLOG, 128);
server.childOption(ChannelOption.SO_KEEPALIVE, true);
try {
ChannelFuture cf = server.bind(host, port).sync();
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
shutdown();
}
}
/**
* 服务器端消息处理
*/
static class TcpServerHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("客户端消息>>>> " + msg);
ctx.channel().writeAndFlush("您好,客户端,我是服务器端。");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
/**
* 关闭
*/
protected static void shutdown() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
/**
* @param args
*/
public static void main(String[] args) {
// 服务地址
String ip = "0.0.0.0";
// 端口
int port = 54321;
TcpServer.run(ip,port);
}
}
客户端实现代码:package what21.netty.tcp;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
public class TcpClient {
/**
* 初始化Bootstrap
*
* @return
*/
public static final Bootstrap getBootstrap() {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder",
new LengthFieldPrepender(4));
pipeline.addLast("decoder",
new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder",
new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new TcpClientHandler());
}
});
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
return bootstrap;
}
/**
* 客户器端消息处理
*/
static class TcpClientHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("服务器端消息>>>> " + msg);
Thread.sleep(2*1000);
ctx.writeAndFlush("你好,我是客户端");
}
}
/**
* @param host
* @param port
* @return
*/
public static final Channel getChannel(String host,int port){
Channel channel = null;
try {
channel = getBootstrap().connect(host, port).sync().channel();
} catch (Exception e) {
return null;
}
return channel;
}
/**
* @param ip
* @param port
* @throws Exception
*/
public static void sendMsg(String ip,int port) throws Exception {
Channel channel = getChannel(ip,port);
if(channel!=null){
channel.writeAndFlush("你好,我是客户端").sync();
}else{
System.err.println("消息发送失败,连接尚未建立成功!");
}
}
/**
* @param args
*/
public static void main(String[] args) {
try {
TcpClient.sendMsg("127.0.0.1", 54321);
} catch (Exception e) {
e.printStackTrace();
}
}
}
java netty教程_Netty4.1初学者教程(HelloWorld教程)相关推荐
- java tutorial mobi_Java 初学者List集合教程
# Java 初学者`List`集合教程 > 原文: [https://javabeginnerstutorial.com/core-java-tutorial/list-collection- ...
- 一个适合初学者的Ant教程
一个适合初学者的Ant教程 一,构建ant环境 要使用ant首先要构建一个ant环境,步骤很简单: 1),安装jdk,设置JAVA_HOME ,PATH ,CLASS_PATH(这些应该是 ...
- matlab初学者教程_初学者的Hibernate教程
matlab初学者教程 Welcome to the Hibernate tutorial for Beginners. Hibernate is one of the most widely use ...
- C#基础教程-c#实例教程,适合初学者
C#基础教程-c#实例教程,适合初学者. 第一章 C#语言基础 本章介绍C#语言的基础知识,希望具有C语言的读者能够基本掌握C#语言,并以此为基础,能够进一步学习用C#语言编写window应用程序和W ...
- 史上最全的Android开发学习教程集锦【初学者】
根据Google的报告,截止2017年5月为止,Android活跃用户已超过20亿,并还在持续增长中.Android系统在几个主要的市场上已超过了iOS系统,特别是在美国,欧洲和日本,然而苹果确实在中 ...
- Angular 初学者快速上手教程
课程介绍 本课程是一个系列基础教程,目标是带领读者上手实战,课程以新版本 Angular 的 3 个核心概念作为主线:组件.路由.模块,加上业务开发过程中必须用到的特性:工具.指令.表单.RxJS.i ...
- java和php哪个运行更快,java和php哪个入门快?-php教程
跟着互联网的高速倒退,愈来愈多的人开端抉择处置较量争论机行业,而想要处置相干工作的话,理解相干编程言语也是必备的一项技艺.可是有不少冤家正在抉择要学习的编程言语时就被难到了,想晓得哪一种言语入门更快, ...
- 【Unity3D基础教程】给初学者看的Unity教程(四):通过制作Flappy Bird了解Native 2D中的RigidBody2D和Collider2D...
作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点[推荐].谢谢! 引子 在第一篇文章[Unity3D基础教程] ...
- RNN 怎么用?给初学者的小教程
RNN 怎么用?给初学者的小教程 机器之心 Synced 08月14日 18:06 RNN 深度学习 机器翻译 分类 :互联网 阅读:559 抢沙发 . 什么是循环神经网络(RNN),如何使用它 ...
最新文章
- GalHttprequest类库简介——android平台上的一个轻量级的http网络请求及缓存框架
- HTTP Error 503. The service is unavailable.
- mnist 0与mnist x 相互衰变半衰期汇总
- CCHP分布式能源技术在数据中心IDC的应用
- vb定义模块且使用模块_ET200S 1 STEP 步进模块使用入门
- 如何理解Library List
- jdk1.8新特性(五)——Stream
- 二分查找和折半插入排序一块说说-很合适~~~
- srsLTE源码学习:度量中心:metrics_hub.h
- 【多线程】Semaphore:实现快速限流器
- 马士兵_JAVA自学之路(为那些目标模糊的码农们)
- Java关键字表格、Java有哪些关键字?
- 如何快捷修改eclipse黑色背景和字体颜色设置?
- python猜硬币正反面_python 编写猜硬币小游戏
- Relatively Prime Graph CodeForces - 1009D
- vue通过disabled控制按钮的置灰
- 阅读笔记--神经网络与深度学习(邱锡鹏)
- Win10 家庭版 升级至 专业版
- el-table表格数据 中文 键值渲染
- 信号调理方式(放大、滤波、隔离、调制解调等)