关于netty的简单实现
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的简单实现的更多相关文章
- Netty学习——基于netty实现简单的客户端聊天小程序
Netty学习——基于netty实现简单的客户端聊天小程序 效果图,聊天程序展示 (TCP编程实现) 后端代码: package com.dawa.netty.chatexample; import ...
- netty 实现简单的rpc调用
yls 2020/5/23 netty 实现简单rpc准备 使用netty传输java bean对象,可以使用protobuf,也可以通过json转化 客户端要将调用的接口名称,方法名称,参数列表的类 ...
- netty的简单的应用例子
一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...
- Netty心跳简单Demo
前面简单地了解了一下IdleStateHandler,我们现在写一个简单的心跳demo: 1)服务器端每隔5秒检测服务器端的读超时,如果5秒没有接受到客户端的写请求,也就说服务器端5秒没有收到读事件, ...
- Netty构建游戏服务器(三)--netty spring简单整合
一,基本方法 上节实现了netty的基本连接,这节加入spring来管理netty,由spring来开启netty服务. 在netty服务器中,我们建立了三个类:HelloServer(程序主入口) ...
- Netty+WebSocket简单实现网页聊天
基于Netty+WebSocket的网页聊天简单实现 一.pom依赖 <dependency> <groupId>io.netty</groupId> ...
- Java使用Netty实现简单的RPC
造一个轮子,实现RPC调用 在写了一个Netty实现通信的简单例子后,萌发了自己实现RPC调用的想法,于是就开始进行了Netty-Rpc的工作,实现了一个简单的RPC调用工程. 如果也有兴趣动手造轮子 ...
- Netty学习笔记之一(Netty解析简单的Http Post Json 请求)
一,HTTP解码器可能会将一个HTTP请求解析成多个消息对象. ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast( ...
- Netty实例-简单的服务端-client实现,凝视具体
书籍推荐: 实例代码 :http://download.csdn.net/detail/jiangtao_st ...
- Netty实现简单HTTP代理服务器
自上次使用Openresty+Lua+Nginx的来加速自己的网站,用上了比较时髦的技术,感觉算是让自己的网站响应速度达到极限了,直到看到了Netty,公司就是打算用Netty来替代Openresty ...
随机推荐
- CPU问题定位与解决
CPU问题定位基本流程: 性能计数器诊断 主要用到的性能计数器 %Process Time 全实例 (主要用于查看当前服务器的CPU 情况) %Process Time sqlservr (主要用 ...
- POJ 2488 A Knight's Journey【DFS】
补个很久之前的题解.... 题目链接: http://poj.org/problem?id=2488 题意: 马走"日"字,让你为他设计一条道路,走遍所有格,并输出字典序最小的一条 ...
- HDU 5667 Sequence
指数有递推式,可以通过矩阵快速幂来求解.再用下面这公式快速幂取模即可. (C是素数) #include<cstdio> #include<cstring> #include&l ...
- Java日志框架-logback配置文件参考(转)
logback.xml <!-- if debug set to true, context info always print otherwise the contex info will p ...
- 报错: The type ByteInputStream is not accessible due to restriction on required library
报错: Access restriction:The type JPEGCodec is not accessible due to restriction on required library C ...
- maven之发布项目到nexus【clean deploy命令】
原文:http://m.blog.csdn.net/article/details?id=49667971 当我们的项目开发完成以后,可能要进行发布(如果是独立的项目,就不需要发布啦,如果是模块项目, ...
- C# DataGridView,右键单击RowHeader时显示右键菜单怎么做?
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { ...
- Go---Redis连接池
之前一篇文章介绍过使用redigo连接redis数据库处理,在使用中发现如果初始化一条链接连接redis做相关操作,使用中发现当两个程序交替使用redis时,先前建立的链接会断掉,只能每次操作的时候重 ...
- Meteor核心API
在本教程中,我们将介绍学习Meteor核心API. 如果你想限制代码只在服务器或客户端可以使用下面的代码运行 - meteorApp.js if (Meteor.isClient) { // Code ...
- Javascript 运行机制
先看一下下面这段js代码: console.log('1'); setTimeout(function(){ console.log('2'); },0); console.log('3'); 请问打 ...