02_Netty实现的Echo服务器和客户端
【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服务器和客户端的更多相关文章
- Linux网络编程--多线程实现echo服务器与客户端“一对多”功能,是网络编程的“Hello World!”
在linux平台下,用多线程实现echo服务器与客户端“一对多”(即是一台服务器可以响应多个客户端的请求).本人写了个demo,和大家一起分享,有不足的地方,请多多指教,我是壮壮熊. 编译时,在后面加 ...
- netty入坑第一步:了解netty和编写简单的Echo服务器和客户端
早期java API通过原生socket产生所谓的"blocking",大致过程是这样 这种的特点是每次只能处理一个请求,如果要实现多个请求并行,就还要分配一个新的线程来给每个客户 ...
- python echo服务器和客户端(客户端可以用telnet之类的)
发上来记录一下,省得下次再写一遍 服务器:server.py #-*- coding:utf-8 -*- from SocketServer import TCPServer, BaseRequest ...
- boost::asio实现一个echo服务器
以前使用ACE实现Server框架,但是觉得太笨重,决定采用boost.asio来写服务器程序: 1.服务器构建在linux上面:当然也可以在windows下运行 2.io部分采用非阻塞模式.业务逻辑 ...
- 异步Socket服务器与客户端
本文灵感来自Andre Azevedo 在CodeProject上面的一片文章,An Asynchronous Socket Server and Client,讲的是异步的Socket通信. S ...
- 基于EPOLL模型的局域网聊天室和Echo服务器
一.EPOLL的优点 在Linux中,select/poll/epoll是I/O多路复用的三种方式,epoll是Linux系统上独有的高效率I/O多路复用方式,区别于select/poll.先说sel ...
- PostgreSQL编码格式:客户端服务器、客户端、服务器端相关影响
关于字符编码这块,官网链接: https://www.postgresql.org/docs/current/charset.html 刚刚写了几百字的东西因为断网,导致全没有了,重头再写,我就只想记 ...
- SVN服务器和客户端安装教程
SVN是什么?有何用? SVN是Subversion的简称,是一个开放源代码的版本控制系统,相较于RCS.CVS,它采用了分支管理系统,它的设计目标就是取代CVS.互联网上很多版本控制服务已从CVS迁 ...
- 2016windows(10) wamp 最简单30分钟thrift入门使用讲解,实现php作为服务器和客户端的hello world
2016最简单windows(10) wamp 30分钟thrift入门使用讲解,实现php作为服务器和客户端的hello world thrift是什么 最简单解释 thrift是用来帮助各个编程语 ...
随机推荐
- Exponentiation POJ-1001
http://poj.org/problem?id=1001 //10000000 100000 #include<iostream> #include<cstring> us ...
- 20190418 CentOS7实用技能综合:系统安装 + WinScp客户端连接 + 防火墙端口号iptables + Nginx编译安装 + MySQL编译安装 + Redis编译安装 + MongoDB编译安装 + ActiveMQ/RocketMQ/RabbitMQ编译安装 + ...各类常用生产环境软件的编译安装
系统安装 + WinScp客户端连接 + 防火墙端口号iptables + Nginx编译安装 + MySQL编译安装 + Redis编译安装 + MongoDB编译安装 + ActiveMQ/Roc ...
- golang在gitlab中的工作流
在敏捷开发的时代, 快速的编码, code review, 测试, 部署, 是提升程序员效率的关键. 同时在基础工具完备的如今, 我们甚至无需过多的操作就可以轻松实现上述步骤, 本文就以gitlab为 ...
- Mac 10.12安装流量监控软件Magican
说明:Magican这家公司已经不维护了,但是软件是单机版的,可以正常使用,但是有些10.12的机器应该是无法看到每个进程的明细,总速度可以正常显示. 下载: (链接: https://pan.bai ...
- css hack 汇整
针对Chrome和Safari等Webkit核心浏览器的CSS hack代码: @media screen and (-webkit-min-device-pixel-ratio:0) { …… } ...
- 查看和修改mysql数据库的最大链接数据
通常,mysql的最大连接数默认是100, 最大可以达到16384.1.查看最大连接数:show variables like '%max_connections%';2.修改最大连接数方法一:修改配 ...
- 初始设置ubuntu 16.04 Vps部署rails
参考 https://blog.longwin.com.tw/2005/12/ssh_keygen_no_passwd/ 1 选择搬瓦工左边菜单栏中的“Root password modificati ...
- OSI及TCP/IP的概念和区别
什么是TCP/IP协议 TCP/IP协议(Transfer Controln Protocol/Internet Protocol)叫做传输控制/网际协议,又叫网络通讯协议,这个协议是Internet ...
- Ruby(1):入门
安装: 一般来说linux会自动装ruby,可以通过: ruby -v 来查看ruby版本 直接使用ruby命令的话,是用来执行ruby文件的.如果要打开交互式ruby解释器.只需要在控制台输入:ir ...
- vue+vuex+axios从后台获取数据存入vuex,组件之间共享数据
在vue项目中组件间相互传值或者后台获取的数据需要供多个组件使用的情况很多的话,有必要考虑引入vuex来管理这些凌乱的状态,今天这边博文用来记录这一整个的过程,后台api接口是使用webpack-se ...