第一个Netty程序
netty就是一个高性能的NIO框架,用于java网络编程。下面说说思路:
服务端:
开启通道、设置网络通信方式、设置端口、设置接收请求的handler、绑定通道、最后关闭
客户端:
开启通道、设置网络通信方式、设置服务器ip和端口、设置处理数据的handler、连接服务器、最后关闭。
pom.xml引用如下:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.28.Final</version>
</dependency>
服务端总共两个类,EchoServer.java和EchoServerHandler.java。
EchoServer.java
package cn.enjoyedu.ch02.echo; 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; /** *
* 创建日期:2018/08/25
* 类说明:
*/
public class EchoServer { private final int port; public EchoServer(int port) {
this.port = port;
} public static void main(String[] args) throws InterruptedException {
int port = 9999;
EchoServer echoServer = new EchoServer(port);
System.out.println("服务器即将启动");
echoServer.start();
System.out.println("服务器关闭");
} public void start() throws InterruptedException {
final EchoServerHandler serverHandler = new EchoServerHandler();
/*线程组*/
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();/*服务端启动必备*/
b.group(group)
/*指明使用NIO进行网络通讯*/
.channel(NioServerSocketChannel.class)
/*指明服务器监听端口*/
.localAddress(new InetSocketAddress(port))
/*接收到连接请求,新启一个socket通信,也就是channel,每个channel
* 有自己的事件的handler*/
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
});
ChannelFuture f = b.bind().sync();/*绑定到端口,阻塞等待直到连接完成*/
/*阻塞,直到channel关闭*/
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
} }
EchoServerHandler.java
package cn.enjoyedu.ch02.echo; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil; /**
* 创建日期:2018/08/25
* 类说明:自己的业务处理
*/
/*指明我这个handler可以在多个channel之间共享,意味这个实现必须线程安全的。*/
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter { /*** 服务端读取到网络数据后的处理*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf in = (ByteBuf)msg;/*netty实现的缓冲区*/
System.out.println("Server Accept:"+in.toString(CharsetUtil.UTF_8));
ctx.write(in);
} /*** 服务端读取完成网络数据后的处理*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)/*flush掉所有的数据*/
.addListener(ChannelFutureListener.CLOSE);/*当flush完成后,关闭连接*/
} /*** 发生异常后的处理*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
客户端总共两个类,EchoClient.java和EchoClientHandler.java
EchoClient.java
package cn.enjoyedu.ch02.echo; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; /**
* 创建日期:2018/08/26
* 类说明:netty的客户端
*/
public class EchoClient { private final int port;
private final String host; public EchoClient(int port, String host) {
this.port = port;
this.host = host;
} public void start() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
try {
Bootstrap b = new Bootstrap();/*客户端启动必备*/
b.group(group)
.channel(NioSocketChannel.class)/*指明使用NIO进行网络通讯*/
.remoteAddress(new InetSocketAddress(host,port))/*配置远程服务器的地址*/
.handler(new EchoClientHandler());
ChannelFuture f = b.connect().sync();/*连接到远程节点,阻塞等待直到连接完成*/
/*阻塞,直到channel关闭*/
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
} public static void main(String[] args) throws InterruptedException {
new EchoClient(9999,"127.0.0.1").start();
}
}
EchoClientHandler.java
package cn.enjoyedu.ch02.echo; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil; /**
* 创建日期:2018/08/26
* 类说明:
*/
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /*客户端读取到数据后干什么*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
throws Exception {
System.out.println("Client accetp:"+msg.toString(CharsetUtil.UTF_8));
} /*客户端被通知channel活跃以后,做事*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//往服务器写数据
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello,Netty",
CharsetUtil.UTF_8));
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
} }
代码里面也有具体的注释。
第一个Netty程序的更多相关文章
- Netty(1):第一个netty程序
为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...
- 第二章:第一个Netty程序
第一步:设置开发环境 • 安装JDK,下载地址http://www.oracle.com/technetwork/java/javase/archive-139210.html • 下载netty ...
- 搭建第一个netty程序
来自action In netty 自己修改一点点 主要依赖 <dependencies> <dependency> <groupId>io.netty</g ...
- Netty In Action中国版 - 第二章:第一Netty程序
本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...
- Netty4具体解释二:开发第一个Netty应用程序
既然是入门,那我们就在这里写一个简单的Demo,client发送一个字符串到server端,server端接收字符串后再发送回client. 2.1.配置开发环境 1.安装JDK 2.去官网下 ...
- Netty入门二:开发第一个Netty应用程序
Netty入门二:开发第一个Netty应用程序 时间 2014-05-07 18:25:43 CSDN博客 原文 http://blog.csdn.net/suifeng3051/article/ ...
- 创建安全的 Netty 程序
1.使用 SSL/TLS 创建安全的 Netty 程序 SSL 和 TLS 是众所周知的标准和分层的协议,它们可以确保数据时私有的 Netty提供了SSLHandler对网络数据进行加密 使用Http ...
- 一个老牌程序员说:做Java开发,怎么可以不会这 20 种类库和 API
- 「Netty实战 02」手把手教你实现自己的第一个 Netty 应用!新手也能搞懂!
大家好,我是 「后端技术进阶」 作者,一个热爱技术的少年. 很多小伙伴搞不清楚为啥要学习 Netty ,今天这篇文章开始之前,简单说一下自己的看法: @ 目录 服务端 创建服务端 自定义服务端 Cha ...
随机推荐
- SqlServer字符串拼接
ID Name 2 小红 2 小明 2 小青 3 大红 3 大明 3 大青 有一张这样的表,现在要达到 把ID为2的Name合拼成一行显示出来: step1:建函数 CREATE FUNCTI ...
- mint-ui之datetime-picker使用
一基本使用<template> <mt-datetime-picker ref="picker" type="time" v-model=&q ...
- 在C#中使用OpenCV(使用OpenCVSharp)
在C#中使用OpenCV(使用OpenCVSharp) 1.什么是OpenCVSharp 为了解决在Csharp下编写OpenCV程序的问题,我做过比较深入的研究,并且实现了高效可用的方法 ...
- 关于VS2013下制作和使用静态库和动态库
关于VS2013下制作和使用静态库和动态库 引言 什么是库:库是写好的现有的,成熟的,可以复用的代码. 所谓静态.动态是指链接.将一个程序编译成可执行程序的步骤: 静态库在链接阶段,会将汇编生成的目标 ...
- bzoj 3670 动物园 - kmp - 动态规划
Description 近日,园长发现动物园中好吃懒做的动物越来越多了.例如企鹅,只会卖萌向游客要吃的.为了整治动物园的不良风气,让动物们凭自己的真才实学向游客要吃的,园长决定开设算法班,让动物们学习 ...
- Codeforces 825D Suitable Replacement - 贪心 - 二分答案
You are given two strings s and t consisting of small Latin letters, string s can also contain '?' c ...
- Codeforces Round #427 (Div. 2) Problem A Key races (Codeforces 835 A)
Two boys decided to compete in text typing on the site "Key races". During the competition ...
- CodeChef - MRO Method Resolution Order(打表)
题意:有一种关系叫继承,那么继承父类的同时也会继承他的一个函数f,能继承任意多个父类或不继承,但不能继承自己的子类.现在规定一个列表,这个列表必须以1~N的顺序排列,并且父类不会排在子类后面,1含有一 ...
- (转)renren-fast解读(一)
(二期)8.renren-fast项目解读(一) [课程八]预防xss...注入.xmind0.2MB [课程八预习]开...解读.xmind0.5MB 课程八_日志处理与...模块.xmind0.2 ...
- C# 里调用vb的inputbox弹出窗
https://blog.csdn.net/hutao1101175783/article/details/16800871 先对项目添加对Microsoft.VisualBasic的引用 Inter ...