【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. es6里class类

    /** * Created by issuser on 2018/11/27. *///如果静态方法包含this关键字,这个this指的是类,而不是实例./** (1)类的实例属性 1.类的实例属性可 ...

  2. hibernate多对一单向关联注解方式

    多对一单向关联,在多的一方加上一的一方作为外键.在程序里表现为:在多的一方加上一的引用. 小组类Group,用户User: Group: package com.oracle.hibernate; i ...

  3. SpringBoot集成WebSocket【基于STOMP协议】进行点对点[一对一]和广播[一对多]实时推送

    原文详细地址,有点对点,还有广播的推送:https://blog.csdn.net/ouyzc/article/details/79884688 下面是自己处理的一些小bug 参考原文demo,结合工 ...

  4. jsf和facelets的生命周期

    一.JSF生命周期 JSF是基于事件驱动.JSF生命周期分为两个主要阶段:执行阶段和渲染阶段. 1.执行阶段 分为六个阶段: 恢复视图阶段 当客户端请求一个JavaServer Faces页面时,Ja ...

  5. Kibana插件sentinl实现邮件报警

    为什么会突然想用到对日志的异常内容进行邮件报警,是因为在上周公司的线上业务多次出现锁表,开发在优化sql的同时,我也在想是不是可以对日志的异常内容进行检测并实现邮件预警. 在网上查询了一些资料后,决定 ...

  6. 修复PHP支持的标准JSON数据格式

    PHP的json_decode无法解析的JSON数据,代码如下: $json = "{rst:5,c:[ [1018485,2,0,0,0,0,'','0-0','','',2,0,2],[ ...

  7. jmeter(4)——简单测试流程

    今天通过一个简单的例子梳理一下用jmeter进行测试的流程 1.确定被测网站:gogomall.com 2.制定测试指标:响应时间和错误率 3.设计测试场景 4.具体测试步骤 1>创建一个测试计 ...

  8. JAVA练手--链表

    package tet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; impo ...

  9. shell获取时间的相关命令

    Linux shell获取时间和时间间隔(ms级别) 说明:在进行一些性能测试的时候,有时候我们希望能计算一个程序运行的时间,有时候可能会自己写一个shell脚本方便进行一些性能测试的控制(比如希望能 ...

  10. XmlSerializer序列化

    XmlSerializer在命名空间using System.Xml.Serialization下. 序列化和反序列化的代码: using System.IO; using System.Xml; u ...