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服务,于是便将此整 ...
随机推荐
- linux中grep使用方法具体解释
查找特定字符串并颜色显示 [root@fwq test]# grep -n 'the' regular_express.txt --color=auto 8:I can't finish the te ...
- SQL Server Reporting Services (SQLEXPRESS) 服务占用80端口
win7, 好多时候,看到system进程占用了80端口,这个是系统进程,不能直接结束.我们不知道这个进程的哪个服务占用了80端口,这里记录其中一个服务"SQL Server Reporti ...
- UVA 12219 Common Subexpression Elimination
题意: 求最小的表达式树,也就是把相同的表达式子树给替换成最前面相同的编号. 分析: 用map<string,int>smp;存放子树对应的字符串,如果以后出现相同的子树则用相同编号表示. ...
- Jquery二级简单折叠菜单
写在前面: 1.前端新手 2.欢迎交流 3. 源代码百度云页面示例链接: http://pan.baidu.com/s/1nt0yjd3 链接失效请留言 效果图: 代码部分:jquery部分: < ...
- [翻译]理解 ASP.NET 5
**原文:http://docs.asp.net/en/latest/conceptual-overview/understanding-aspnet5-apps.html** 英文捉急,花了挺多时间 ...
- 用ul、li做横向导航
/* ul li以横排显示 */ /* 所有class为menu的div中的ul样式 */ div.menu ul { list-style:none; /* 去掉ul前面的符号 */ margin: ...
- 总结PHP中几种常用的网页跳转代码
网页跳转的意思就是指当你在浏览器中访问A页面时,会自动跳转到B页面,往往网页跳转用在404页面中会比较多点.至于怎么实现网页跳转,网上已经提供了很多的方法,有些方法是不可行的,经过测试,叶德华今天就在 ...
- BaseAdapter导致notifyDataSetChanged()无效的三个原因及处理方法
原文 http://blog.csdn.net/dawanganban/article/details/21376979 前一段时间在做一个项目的时候遇到了一个关于BaseAdapter的notif ...
- 兼容IE6,IE7和firefox可以使用的一些css hack:
.一些问题是浏览器自身的问题,遇到问题发生无法避免的情况下,那就要考虑使用一些css hack了,以下是针对IE6,IE7和firefox可以使用的一些css hack:(1) a: 针对区别IE6 ...
- modbus rtu 协议转DLT645-2007和DLT645-1997电表协议转换器定制,
现场会碰到现场数据为Modbus协议,但是后台系统为DLT645协议系统,本模块支持将工业ModbusRtu协议转换为电表国标协议DLT645协议,支持1997和2007俩种标准,只需要进行简单的配置 ...