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 学习(一)的更多相关文章

  1. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

  2. Netty4.0学习笔记系列之二:Handler的执行顺序(转)

    http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...

  3. Netty4.0学习笔记系列之三:构建简单的http服务(转)

    http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.C ...

  4. Netty4.0学习教程

    http://blog.csdn.net/u013252773/article/details/21046697 一些属性和方法介绍 http://blog.csdn.net/zxhoo/articl ...

  5. Netty4.0学习笔记系列之四:混合使用coder和handler

    Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它 ...

  6. Netty4.0学习笔记系列之二:Handler的执行顺序

    Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...

  7. Netty实现丢弃服务协议(Netty4.X学习一)

    何为丢弃服务(Discard Protocol),丢弃服务就是一个协议,是最简单的协议,它的作用是接受到什么就丢弃什么,它对调试网路状态有一定的用处.基于TCP的丢弃服务,服务器实现了丢弃丢弃协议,服 ...

  8. Netty4 学习笔记之一:客户端与服务端通信 demo

    前言 因为以前在项目中使用过Mina框架,感受到了该框架的强大之处.于是在业余时间也学习了一下Netty.因为Netty的主要版本是Netty3和Netty4(Netty5已经被取消了),所以我就直接 ...

  9. Netty4 学习笔记之四: Netty HTTP服务的实现

    前言 目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2,更早的有JSP/servlet. 在学习Netty的时候,发现Netty 也可以作HTTP服务,于是便将此整 ...

随机推荐

  1. Linux挂载硬盘出错:$LogFile indicates unclean shutdown (0, 0)

    前一次还挂载好好的,今天在挂载NTFS的分区就不行了,出现如下错误信息和提示: $LogFile indicates unclean shutdown (0, 0) Mount is denied b ...

  2. Struts2 访问web元素

    访问web元素的四种方法(耦合,依赖注入).(耦合,非依赖注入).(非耦合,依赖注入).(非耦合,非依赖注入) 耦合:可以得到HttpServletResponse,HttpServletReques ...

  3. iOS中有关配置 Apache 服务器的详细步骤

    配置 Apache 服务器 目的: 能够有一个测试的服务器,Apache 服务器是免费的! 为什么是 Apache 使用最广的 Web 服务器 Mac自带,只需要修改几个配置就可以,简单,快捷 有些特 ...

  4. 清除float常用方法(:after和clear:both)

    参考网址:http://jingyan.baidu.com/article/c74d60006bea410f6a595d17.html .clearfix:after{ .....}  和 .clea ...

  5. java之方法覆盖的坑

    昨天写了个小例子,覆盖hashCode.equals进行集合set的一些特性测试,代码如下: class Test3 { public int c; public Test3(int c) {this ...

  6. Inno setup卸载前退出进程、删除文件夹

    [Code]function InitializeUninstall(): Boolean; var MainRun: HWND; var MVRun:HWND; begin// FindWindow ...

  7. Linux下Matlab崩溃的解决方法

    猜想主要是因为图形显示用了OpenGL加速造成不稳定. 我的运行环境是: Ubuntu 10.04 LTS 64bit Matlab R2010b 解决方法是启动时用: $MATLAB_DIR/bin ...

  8. Scrapy的架构初探

    Scrapy,Python开发的一个web抓取框架. 1,引言 Python即时网络爬虫启动的目标是一起把互联网变成大数据库.单纯的开放源代码并不是开源的全部,开源的核心是“开放的思想”,聚合最好的想 ...

  9. Oracle EBS-SQL (PO-10):检查过期采购未接收订单.sql

    Select pha.segment1               采购订单,            MSI.SEGMENT1             物料编码,           MSI.DESC ...

  10. .NET日志工具介绍

    最近项目需要一个日志工具来跟踪程序便于调试和测试,为此研究了一下.NET日志工具,本文介绍了一些主流的日志框架并进行了对比.发表出来与大家分享. 综述 所谓日志(这里指程序日志)就是用于记录程序执行过 ...