【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. python全栈开发_day13_迭代器和生成器

    一:迭代器 1)可迭代对象 具有内置函数__iter__的数据就是可迭代对象 2)迭代器对象 具有内置函数__next__的数据就是迭代器对象 迭代器对象一定是可迭代对象,可迭代对象不一定是迭代器对象 ...

  2. 学习GO第一天,自我感觉可麻利的开干了-GO语言配置、开发、服务器部署

    学习GO第一天,自我感觉可麻利的开干了-GO语言配置.开发.服务器部署 第一步下载 go sdk https://golang.org/dl/ https://storage.googleapis.c ...

  3. 使用NHibernate(1)--资料汇总

    NHibernate最新版本是4.0,目前还只是alpha版,没有发布.稳定版本是3.3,项目中用的也是这个版本,所以以后的介绍都是基于这个版本的. 在网上找了一下相关的学习资料,现汇总如下: NHi ...

  4. 高性能的数据压缩库libzling-20160105

    libzling(https://github.com/richox/libzling,求观看[watch],求星[star],求叉[fork])是一款高性能的数据压缩库,参见原贴:http://ww ...

  5. python爬虫的教程

    来源:http://cuiqingcai.com/1052.html 大家好哈,我呢最近在学习Python爬虫,感觉非常有意思,真的让生活可以方便很多.学习过程中我把一些学习的笔记总结下来,还记录了一 ...

  6. python 多线程与GIL

    GIL 与 Python 线程的纠葛 GIL 是什么?它对 python 程序会产生怎样的影响?我们先来看一个问题.运行下面这段 python 代码,CPU 占用率是多少? # 请勿在工作中模仿,危险 ...

  7. [转载]VS2010怎样打开VS2013或者VS2015建立的工程

    VS2010怎样打开VS2013或者VS2015建立的工程 作用:解决vs低版本无法直接打开高版本的工程文件问题. 一.转载出处 http://blog.csdn.net/qq2399431200/a ...

  8. hibernate与ibatis的区别

    Hibernate 是当前最流行的O/R mapping框架,当前版本是3.05.它出身于sf.net,现在已经成为Jboss的一部分了 iBATIS 是另外一种优秀的O/R mapping框架,当前 ...

  9. Python DataFrame导出CSV、数据库

    写入Oracle from sqlalchemy import create_engine import pandas as pd import numpy as np df = pd.DataFra ...

  10. 搭建nginx代理,为前端页面跨域调用接口

    前端同学因开发需要,本地搭建的服务需要调用其它域名的接口,在帮助正确配置后,已能正常使用. 这里写一篇博客,记录一下. 前端页面地址为127.0.0.1:9813/a.html 接口地址http:// ...