【Echo服务端】

【EchoServer】

public class EchoServer {
private final int port; public EchoServer(int port) {
this.port = port;
} public static void main(String[] args) throws Exception {
new EchoServer(9999).start();
} public void start() throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); //创建ServerBootstrap
b.group(group)
.channel(NioServerSocketChannel.class) //指定NIO的传输Channel
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new EchoServerHandler()); //添加EchoServerHandler到Channel的ChannelPipeline
}
});
ChannelFuture future = b.bind().sync(); //绑定服务器,sync等待服务器关闭
System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
} }

【EchoServerHandler】

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
System.out.println("Server received:"+in.toString(CharsetUtil.UTF_8));
ctx.write(in);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Server is Active......");
} }

[ 说明 ]

Echo的Handler实现了服务器的业务,决定了连接创建以后和收到信息后该如何处理。

ChannelInboundHandler的实现方法作用
channelRead() //每次收到信息都会回调
channelReadComplete() //channelRead执行结束时回调
exceptionCaught() //执行异常情况下会被回调。

【Echo客户端】

【EchoClient】

public class EchoClient {

    private final String host;
private final int port; public EchoClient(String host, int port) {
this.host = host;
this.port = port;
} public static void main(String[] args) throws Exception{
new EchoClient("127.0.0.1",9999).start();
} public void start() throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host,port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(
new EchoClientHandler()
);
}
});
ChannelFuture future = b.connect().sync();
future.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}

【EchoClientHandler】

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client is active......");
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
} @Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
System.out.println("client received:"+ in.toString(CharsetUtil.UTF_8));
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} }

【运行结果】

[ 服务端 ]

[ 客户端 ]

02_Netty实现的Echo服务器和客户端的更多相关文章

  1. Linux网络编程--多线程实现echo服务器与客户端“一对多”功能,是网络编程的“Hello World!”

    在linux平台下,用多线程实现echo服务器与客户端“一对多”(即是一台服务器可以响应多个客户端的请求).本人写了个demo,和大家一起分享,有不足的地方,请多多指教,我是壮壮熊. 编译时,在后面加 ...

  2. netty入坑第一步:了解netty和编写简单的Echo服务器和客户端

    早期java API通过原生socket产生所谓的"blocking",大致过程是这样 这种的特点是每次只能处理一个请求,如果要实现多个请求并行,就还要分配一个新的线程来给每个客户 ...

  3. python echo服务器和客户端(客户端可以用telnet之类的)

    发上来记录一下,省得下次再写一遍 服务器:server.py #-*- coding:utf-8 -*- from SocketServer import TCPServer, BaseRequest ...

  4. boost::asio实现一个echo服务器

    以前使用ACE实现Server框架,但是觉得太笨重,决定采用boost.asio来写服务器程序: 1.服务器构建在linux上面:当然也可以在windows下运行 2.io部分采用非阻塞模式.业务逻辑 ...

  5. 异步Socket服务器与客户端

      本文灵感来自Andre Azevedo 在CodeProject上面的一片文章,An Asynchronous Socket Server and Client,讲的是异步的Socket通信. S ...

  6. 基于EPOLL模型的局域网聊天室和Echo服务器

    一.EPOLL的优点 在Linux中,select/poll/epoll是I/O多路复用的三种方式,epoll是Linux系统上独有的高效率I/O多路复用方式,区别于select/poll.先说sel ...

  7. PostgreSQL编码格式:客户端服务器、客户端、服务器端相关影响

    关于字符编码这块,官网链接: https://www.postgresql.org/docs/current/charset.html 刚刚写了几百字的东西因为断网,导致全没有了,重头再写,我就只想记 ...

  8. SVN服务器和客户端安装教程

    SVN是什么?有何用? SVN是Subversion的简称,是一个开放源代码的版本控制系统,相较于RCS.CVS,它采用了分支管理系统,它的设计目标就是取代CVS.互联网上很多版本控制服务已从CVS迁 ...

  9. 2016windows(10) wamp 最简单30分钟thrift入门使用讲解,实现php作为服务器和客户端的hello world

    2016最简单windows(10) wamp 30分钟thrift入门使用讲解,实现php作为服务器和客户端的hello world thrift是什么 最简单解释 thrift是用来帮助各个编程语 ...

随机推荐

  1. Linux文件索引节点相关概念

    一.  概念 1.  inode(index node)表中包含文件系统所有文件列表 一个节点 (索引节点)是在一个表项,包含有关文件的信息( 元数据 ),包括: 文件类型,权限,UID,GID 链接 ...

  2. 开源单点登录系统CAS入门

    一.什么是CAS CAS 是 Yale 大学发起的一个开源项目,旨在为 Web 应用系统提供一种可靠的单点登录方法,CAS 在 2004 年 12 月正式成为 JA-SIG 的一个项目.CAS 具有以 ...

  3. resetBuffer方法与reset方法的使用场景:解决生成HTML或者文件下载时的首部空白行的问题

    getResponse的getWriter()方法 getResponse的getWriter()方法连续两次输出流到页面的时候,第二次的流会包括第一次的流,所以可以使用response.reset或 ...

  4. mono for android读书笔记之硬件编程(转)

    本章将会介绍: 传感器的API 加速器编程,设备的方向,近场检测 网络编程 蓝牙编程 上述的技术的应用场景很多,比如: 1.检测当前的网络是否可用,并提醒用户,检测当前的网络类型,比如Wifi.3G. ...

  5. 16个最佳响应式HTML5框架分享

    HTML5框架可以快速构建响应式网站,它们帮助程序员减少编码工作,减少冗余的代码.如今有很多免费的HTML5框架可供使用,由于它们有着响应式设计.跨浏览器兼容.相对轻量级等特点,这些框架在开发中都十分 ...

  6. linux 下 vi 编辑器 使用

    命令模式(command mode).插入模式(Insert mode)和底行模式(last line mode) 1.进入插入模式 按「i」切换进入插入模式「insert mode」,按“i”进入插 ...

  7. zend studio 连PHP自带系统函数 常量都不提示

    如果是新建项目,所有PHP文件里面函数都是可以自带提示的. 但是,打开已经建立好的项目时候,貌似无法识别是PHP项目或者其他什么. 此时,在项目上点击: configure->add php s ...

  8. PHP 中 strlen 获取中英 字符长度 以作以后对比使用

    ANSII编码: 1 长度是3 a 长度是3 ? 长度是3 我 长度是4 ?长度是2 ---------------------------- UTF-8编码: 1 长度是1 a长度是1 ? 长度是1 ...

  9. JavaScript数据结构-8.双向链表

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. graphql pass arg

    ; ; var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("POST", "http ...