【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. localStorage注册页面A注册数据在本地储存并在B页面打开

    如题目的这么一个问题, A页面代码 <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  2. 01背包-记忆化搜索到成型的DP

    记忆化搜索 #include<bits/stdc++.h> using namespace std; typedef long long ll; int n,W; int dp[105][ ...

  3. js数字格式化为千分位

    方法1: 浏览器自带的一个方法 const num=12345.6789 num.toLocaleString();=>"12,345.679" 方法2: 正则匹配 func ...

  4. java容器类1:Collection,List,ArrayList,LinkedList深入解读

    1. Iterable 与 Iterator Iterable 是个接口,实现此接口使集合对象可以通过迭代器遍历自身元素. public interface Iterable<T> 修饰符 ...

  5. Python爬虫学习:Python内置的爬虫模块urllib库

    urllib库 urllib库是Python中一个最基本的网络请求的库.它可以模拟浏览器的行为发送请求(都是这样),从而获取返回的数据 urllib.request 在Python3的urllib库当 ...

  6. hibernate的AnnotationHelloWorld

    来龙去脉: 最开始sun这个土鳖设计了EJB2.0.EJB2.1那个时代.后来有人发现设计的很烂,不好用,就设计了hibernate,,人们发现用hibernate反而比EJB2.0.2.1好,hib ...

  7. 20.Class的继承

    1.简介 Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多 class Point { } class ColorPoint extends ...

  8. SpringMVC 的工作机制

    在一个工程中如果想要使用 SpringMVC的话,只需要两个步骤 在web.xml中配置一个DispatcherServlet.需要配置一个org.springframework.web.servle ...

  9. WPF的Label默认的padding不为0

    1.如图: 要求让“Tools” 左对齐,代码中已设置:HorizontalContentAlignment="Left" <Label Foreground="W ...

  10. Comet:基于 HTTP 长连接的“服务器推”技术(转载)

    “服务器推”技术的应用 传统模式的 Web 系统以客户端发出请求.服务器端响应的方式工作.这种方式并不能满足很多现实应用的需求,譬如: 监控系统:后台硬件热插拔.LED.温度.电压发生变化: 即时通信 ...