1. 新建两个maven项目, 分别为

netty-server: netty的服务端: 消息的消费者
netty-client: netty的客户端: 消息的生产者

2. 分别引入netty的maven依赖

 <dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>

3. netty-server服务端

3.1. 服务端引导类

 public class EchoServer {

     private int port;

     private EchoServer(int port) {
this.port = port;
} private void start() throws Exception {
System.out.println("Echo Server Start");
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
});
ChannelFuture f = b.bind().sync();
System.out.println("Server Start Listen At: " + port);
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new EchoServer(port).start();
}
}

3.2. 服务端消息消费业务

 public class EchoServerHandler extends ChannelInboundHandlerAdapter {

     @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf bb = (ByteBuf) msg;
bb.markReaderIndex();
System.out.println("Server Received: " + ByteBufUtil.hexDump(bb.readBytes(bb.readableBytes())));
bb.resetReaderIndex();
ctx.write(msg);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

4. netty-client客户端

4.1. 客户端引导类

 public class EchoClient {
private String host;
private int port; private EchoClient(String host, int port) {
this.host = host;
this.port = port;
} private void start() throws Exception {
System.out.println("Echo Client Start");
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
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
}); ChannelFuture f = b.connect().sync();
System.out.println("Server Client Listen Host: [" + host + "] And Port: [" + port + "]");
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8080;
int len = 2;
if (args.length == len) {
host = args[0];
port = Integer.parseInt(args[1]);
} new EchoClient(host, port).start();
} }

4.2 客户端消息生产业务

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Rocks!", CharsetUtil.UTF_8));
} @Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
System.out.println("Client Received: " + ByteBufUtil.hexDump(in.readBytes(in.readableBytes())));
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

5. 测试:

5.1. 启动服务端

5.2. 启动客户端

5.3. 再看服务端

关于netty的简单实现的更多相关文章

  1. Netty学习——基于netty实现简单的客户端聊天小程序

    Netty学习——基于netty实现简单的客户端聊天小程序 效果图,聊天程序展示 (TCP编程实现) 后端代码: package com.dawa.netty.chatexample; import ...

  2. netty 实现简单的rpc调用

    yls 2020/5/23 netty 实现简单rpc准备 使用netty传输java bean对象,可以使用protobuf,也可以通过json转化 客户端要将调用的接口名称,方法名称,参数列表的类 ...

  3. netty的简单的应用例子

    一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...

  4. Netty心跳简单Demo

    前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...

  5. Netty构建游戏服务器(三)--netty spring简单整合

    一,基本方法 上节实现了netty的基本连接,这节加入spring来管理netty,由spring来开启netty服务. 在netty服务器中,我们建立了三个类:HelloServer(程序主入口) ...

  6. Netty+WebSocket简单实现网页聊天

    基于Netty+WebSocket的网页聊天简单实现 一.pom依赖 <dependency>        <groupId>io.netty</groupId> ...

  7. Java使用Netty实现简单的RPC

    造一个轮子,实现RPC调用 在写了一个Netty实现通信的简单例子后,萌发了自己实现RPC调用的想法,于是就开始进行了Netty-Rpc的工作,实现了一个简单的RPC调用工程. 如果也有兴趣动手造轮子 ...

  8. Netty学习笔记之一(Netty解析简单的Http Post Json 请求)

    一,HTTP解码器可能会将一个HTTP请求解析成多个消息对象. ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast( ...

  9. Netty实例-简单的服务端-client实现,凝视具体

           书籍推荐:                                       实例代码 :http://download.csdn.net/detail/jiangtao_st ...

  10. Netty实现简单HTTP代理服务器

    自上次使用Openresty+Lua+Nginx的来加速自己的网站,用上了比较时髦的技术,感觉算是让自己的网站响应速度达到极限了,直到看到了Netty,公司就是打算用Netty来替代Openresty ...

随机推荐

  1. 外星联络(bzoj 2251)

    Description 小 P 在看过电影<超时空接触>(Contact)之后被深深的打动,决心致力于寻找外星人的事业.于是,他每天晚上都爬在屋顶上试图用自己的收音机收听外星人发来的信息. ...

  2. [Usaco2007 Oct] Super Paintball超级弹珠

    Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 489  Solved: 384[Submit][Status][Discuss] Description ...

  3. 胜利大逃亡--hdu --1253(bfs)

    Problem Description Ignatius被魔王抓走了,有一天魔王出差去了,这可是Ignatius逃亡的好机会. 魔王住在一个城堡里,城堡是一个A*B*C的立方体,可以被表示成A个B*C ...

  4. 洛谷——P2872 [USACO07DEC]道路建设Building Roads

    P2872 [USACO07DEC]道路建设Building Roads 题目描述 Farmer John had just acquired several new farms! He wants ...

  5. 寒武纪camp网络测试赛

    寒武纪camp网络测试赛 地址:oj点我进入 A(树形dp+树链剖分) 题意: 分析: 考虑树形dp,f0(x)和f1(x)分别表示以x为根的子树,不取x点或取x点的最大合法子集的元素个数 那么对于一 ...

  6. 前后端分离项目shiro的未登录和权限不足

    在前后端分离的项目中.前端代码和后端代码几乎不在同一个目录下,甚至不是在一台服务器上:我这个项目部署在linux.同一台服务器,不同目录下:所有的页面跳转由前台路由,后台只是提供返回的数据: 干货↓  ...

  7. Spring基于Java的JSR-250注解

    以下内容引用自http://wiki.jikexueyuan.com/project/spring/annotation-based-configuration/spring-jsr250-annot ...

  8. FlashFXP绿色版

    http://www.xdowns.com/soft/1/98/2006/Soft_30927.html

  9. Mysql不同存储引擎的表转换方法

    Mysql不同存储引擎的表转换方法 1.Alter table直接修改表的存储引擎,但是这样会导致大量的系统开销,Mysql为此要执行一个就表向新表的逐行复制.在此期间,转换操作可能会占用服务器的所有 ...

  10. 运行mapreduce - java.lang.InterruptedException

    错误日志: 2018-11-19 05:23:51,686 WARN [main] util.NativeCodeLoader (NativeCodeLoader.java:<clinit> ...