Netty4.X 学习(一)
Server:
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil; import com.netty.utils.*; public class HelloServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Log.logInfo(">>>>>> I'm server.");
// System.out.println(">>>>>> I'm server.");
String msg = "Hello world\n";
ByteBuf encoded = ctx.alloc().buffer(msg.length());
encoded.writeBytes(msg.getBytes());
ctx.write(encoded);
ctx.flush();
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
//Log.logInfo("server receive message:" + msg);
// System.out.println("服务器收到的消息:" + msg);
ByteBuf in = (ByteBuf) msg;
try {
if (in.isReadable()) { // (1)
String str = in.toString(CharsetUtil.US_ASCII);
Log.logInfo("server receive message:" + str);
}
} finally {
ReferenceCountUtil.release(msg); // (2)
} }
}
package com.netty.example.PrintHello; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; public class HelloWorldServer {
public static void main(String[] args) {
//EventLoop 代替原来的 ChannelFactory
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
// server端采用简洁的连写方式,client端才用分段普通写法。
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new HelloServerHandler());
}
}).option(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = serverBootstrap.bind(8000).sync();
f.channel().closeFuture().sync();
System.out.println("TCP服务器已启动");
} catch (InterruptedException e) {
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
运行后可以在终端直接通过telnet命令连接:
telnet localhost 8000
client:
package com.netty.example.PrintHello;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil; public class HelloClientHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(">>>>> I'm client.");
// ctx.write("Hello world!");
// ctx.flush();
String msg = "Are you ok?";
ByteBuf encoded = ctx.alloc().buffer(msg.length());
encoded.writeBytes(msg.getBytes());
ctx.write(encoded);
ctx.flush();
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.println("client收到服务器的消息:" + msg);
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg); // (2)
}
}
}
package com.netty.example.PrintHello; import java.net.InetSocketAddress; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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 io.netty.channel.socket.nio.NioSocketChannel; public class HelloWorldClient {
public static void main(String[] args) {
// Client服务启动器 3.x的ClientBootstrap 改为Bootstrap,且构造函数变化很大,这里用无参构造。
Bootstrap bootstrap = new Bootstrap();
// 指定channel类型
bootstrap.channel(NioSocketChannel.class);
// 指定Handler
bootstrap.handler(new HelloClientHandler());
// 指定EventLoopGroup
bootstrap.group(new NioEventLoopGroup());
// 连接到本地的8000端口的服务端
bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
}
}
Netty4.X 学习(一)的更多相关文章
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序(转)
http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...
- Netty4.0学习笔记系列之三:构建简单的http服务(转)
http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.C ...
- Netty4.0学习教程
http://blog.csdn.net/u013252773/article/details/21046697 一些属性和方法介绍 http://blog.csdn.net/zxhoo/articl ...
- Netty4.0学习笔记系列之四:混合使用coder和handler
Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- Netty实现丢弃服务协议(Netty4.X学习一)
何为丢弃服务(Discard Protocol),丢弃服务就是一个协议,是最简单的协议,它的作用是接受到什么就丢弃什么,它对调试网路状态有一定的用处.基于TCP的丢弃服务,服务器实现了丢弃丢弃协议,服 ...
- Netty4 学习笔记之一:客户端与服务端通信 demo
前言 因为以前在项目中使用过Mina框架,感受到了该框架的强大之处.于是在业余时间也学习了一下Netty.因为Netty的主要版本是Netty3和Netty4(Netty5已经被取消了),所以我就直接 ...
- Netty4 学习笔记之四: Netty HTTP服务的实现
前言 目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2,更早的有JSP/servlet. 在学习Netty的时候,发现Netty 也可以作HTTP服务,于是便将此整 ...
随机推荐
- Windows SQL Server 2012 R2 安装Intel I217-V/I218-V网卡驱动(转)
1.下载Intel官方驱动: https://downloadcenter.intel.com/Detail_Desc.aspx?agr=Y&DwnldID=23071&lang=zh ...
- How to Install/Deinstall Oracle Workspace Manager (文档 ID 263428.1)
In this Document Goal Solution References APPLIES TO: Workspace Manager - Version 9.0.1.0 to 1 ...
- dede 设置为全动态浏览
将织梦所有栏目设置为“使用动态页”,可以再建立栏目时选择“使用动态页”:也可以执行下面的SQL语句.update dede_arctype set isdefault=-1 将网站所有文档都设置为“仅 ...
- linux 系统中的特殊文件
特殊文件是UNIX系统中最具特色的文件特性之一.特殊文件也称设备文件.提供用户访问外部设备,而不必知道各种设备的具体操作.UNIX利用特殊文件作为用户与设备文件的接口,使用户能像访问普通文件那样访问特 ...
- Mvc Webapi+Fiddler调试 (WebAPI 一)
Fiddler Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的“进出”Fiddler的数据(指cookie,html,js, ...
- 解析处理常用json数据总结
工作中用ajax接收到接口返回的数据需要进行解析后操作,这里总结一下平时的方法,用的jquery,复制下来的页面把引入的路径改一下即可. <!DOCTYPE html> <html ...
- android玩耍(-) adbshell安装
一 什么是adbshell http://adbshell.com/ Android Debug Bridge (adb) is a command line tool that lets you c ...
- IO-02
/** 2 *A2-IO-02. 整数四则运算(10) 3 *C语言实现 4 *测试已通过 5 */ #include "stdio.h" #include "stdli ...
- c语言线性表
#include<stdio.h> #include<time.h> #include<stdlib.h> #define MAXSIZE 20 //初始长度 ty ...
- Gentoo Linux 学习笔记1
Gentoo Linux是一个基于portage进行包管理的Linux发行版,最早版本始于2002年.其官方官网为http://www.gentoo.org 目前,Gentoo Linux已 ...