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教程)相关推荐

  1. java tutorial mobi_Java 初学者List集合教程

    # Java 初学者`List`集合教程 > 原文: [https://javabeginnerstutorial.com/core-java-tutorial/list-collection- ...

  2. 一个适合初学者的Ant教程

    一个适合初学者的Ant教程       一,构建ant环境 要使用ant首先要构建一个ant环境,步骤很简单: 1),安装jdk,设置JAVA_HOME ,PATH ,CLASS_PATH(这些应该是 ...

  3. matlab初学者教程_初学者的Hibernate教程

    matlab初学者教程 Welcome to the Hibernate tutorial for Beginners. Hibernate is one of the most widely use ...

  4. C#基础教程-c#实例教程,适合初学者

    C#基础教程-c#实例教程,适合初学者. 第一章 C#语言基础 本章介绍C#语言的基础知识,希望具有C语言的读者能够基本掌握C#语言,并以此为基础,能够进一步学习用C#语言编写window应用程序和W ...

  5. 史上最全的Android开发学习教程集锦【初学者】

    根据Google的报告,截止2017年5月为止,Android活跃用户已超过20亿,并还在持续增长中.Android系统在几个主要的市场上已超过了iOS系统,特别是在美国,欧洲和日本,然而苹果确实在中 ...

  6. Angular 初学者快速上手教程

    课程介绍 本课程是一个系列基础教程,目标是带领读者上手实战,课程以新版本 Angular 的 3 个核心概念作为主线:组件.路由.模块,加上业务开发过程中必须用到的特性:工具.指令.表单.RxJS.i ...

  7. java和php哪个运行更快,java和php哪个入门快?-php教程

    跟着互联网的高速倒退,愈来愈多的人开端抉择处置较量争论机行业,而想要处置相干工作的话,理解相干编程言语也是必备的一项技艺.可是有不少冤家正在抉择要学习的编程言语时就被难到了,想晓得哪一种言语入门更快, ...

  8. 【Unity3D基础教程】给初学者看的Unity教程(四):通过制作Flappy Bird了解Native 2D中的RigidBody2D和Collider2D...

    作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点[推荐].谢谢! 引子 在第一篇文章[Unity3D基础教程] ...

  9. RNN 怎么用?给初学者的小教程

     RNN 怎么用?给初学者的小教程 机器之心 Synced 08月14日 18:06 RNN 深度学习 机器翻译 分类 :互联网 阅读:559 抢沙发 . 什么是循环神经网络(RNN),如何使用它 ...

最新文章

  1. GalHttprequest类库简介——android平台上的一个轻量级的http网络请求及缓存框架
  2. HTTP Error 503. The service is unavailable.
  3. mnist 0与mnist x 相互衰变半衰期汇总
  4. CCHP分布式能源技术在数据中心IDC的应用
  5. vb定义模块且使用模块_ET200S 1 STEP 步进模块使用入门
  6. 如何理解Library List
  7. jdk1.8新特性(五)——Stream
  8. 二分查找和折半插入排序一块说说-很合适~~~
  9. srsLTE源码学习:度量中心:metrics_hub.h
  10. 【多线程】Semaphore:实现快速限流器
  11. 马士兵_JAVA自学之路(为那些目标模糊的码农们)
  12. Java关键字表格、Java有哪些关键字?
  13. 如何快捷修改eclipse黑色背景和字体颜色设置?
  14. python猜硬币正反面_python 编写猜硬币小游戏
  15. Relatively Prime Graph CodeForces - 1009D
  16. vue通过disabled控制按钮的置灰
  17. 阅读笔记--神经网络与深度学习(邱锡鹏)
  18. Win10 家庭版 升级至 专业版
  19. el-table表格数据 中文 键值渲染
  20. 信号调理方式(放大、滤波、隔离、调制解调等)

热门文章

  1. web 播放大华设备(兼容h264,h265),解决谷歌6路播放限制
  2. Android的GridView控件
  3. 纯电小车怎么选?无界Pro让A00级市场有了更高级的选择
  4. python优点是代码库支持、灵活_Python 3.6版本实现用户群的不断增长
  5. 编码器Atom使用指南
  6. F2812 Flash烧写总结
  7. 网络编程_5(超时检测+UNIX域套接字+抓包工具+包头分析)
  8. 详解Everest 命令行参数【转载】
  9. Bzoj4899--记忆的轮廓
  10. 苹果x怎么关闭应用程序_苹果x手机密码忘记了怎么解锁