版本:java7 netty5 protobuf-java-2.5.0
protobuf 消息定义如下:
Auth.proto
option java_package = "com.xinli.netty.protobuf";
package auth;
message AuthRequest{ // (1)
required string user_id=1;
required string password=2;
}
message AuthResponse{ //(2)
required int32 result_code=1;
required string result_message=2;
}
说明:
(1)请求消息,包括用户ID和密码
(2)应答消息,包括响应码和响应说明
服务端:
Auth.java(Auth.proto编译后的java文件) AuthServer.java AuthServerInitHandler.java
AuthServer.java
package com.xinli.netty.protobuf;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthServer {
private static Logger logger = Logger.getLogger(AuthServerInitHandler.class
.getName());
public void start(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();// (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();// (2)
try {
ServerBootstrap b = new ServerBootstrap();// (3)
b.group(bossGroup, workerGroup); // (4)
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//decoded
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
ch.pipeline().addLast(new ProtobufDecoder(Auth.AuthRequest.getDefaultInstance()));
//encoded
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new ProtobufEncoder());
// 注册handler
ch.pipeline().addLast(new AuthServerInitHandler());
}
});
b.option(ChannelOption.SO_BACKLOG, 128);
b.childOption(ChannelOption.SO_KEEPALIVE, true);
//绑定端口 同步等待成功
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
logger.log(Level.INFO, "AuthServer start...");
new AuthServer().start(5555);
}
}
AuthServerInitHandler.java
package com.xinli.netty.protobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthServerInitHandler extends ChannelInboundHandlerAdapter{
private Logger logger=Logger.getLogger(AuthServerInitHandler.class.getName());
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler channelRead");
Auth.AuthRequest request=(Auth.AuthRequest)msg;
System.out.println("request: userId="+request.getUserId()+", password="+request.getPassword());
Auth.AuthResponse response=Auth.AuthResponse.newBuilder()
.setResultCode(0)
.setResultMessage("success")
.build();
ctx.writeAndFlush(response);
//ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler channelReadComplete");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler exceptionCaught");
cause.printStackTrace();
ctx.close();
}
}
客户端:
Auth.java(Auth.proto编译后的java文件) AuthClient.java AuthClientInitHandler.java
AuthClient.java
package com.xinli.netty.protobuf;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
public class AuthClient {
public void connect(String host,int port) throws Exception{
EventLoopGroup workerGroup=new NioEventLoopGroup();
try{
Bootstrap b=new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//decoded
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
ch.pipeline().addLast(new ProtobufDecoder(Auth.AuthResponse.getDefaultInstance()));
//encoded
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new ProtobufEncoder());
// 注册handler
ch.pipeline().addLast(new AuthClientInitHandler());
}
});
ChannelFuture f=b.connect(host, port).sync();
f.channel().closeFuture().sync();
}finally{
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new AuthClient().connect("127.0.0.1", 5555);
}
}
AuthClientInitHandler.java
package com.xinli.netty.protobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthClientInitHandler extends ChannelInboundHandlerAdapter{
private Logger logger=Logger.getLogger(AuthClientInitHandler.class.getName());
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.log(Level.INFO, "AuthClientInitHandler exceptionCaught");
Auth.AuthRequest request=Auth.AuthRequest.newBuilder()
.setUserId("010203")
.setPassword("abcde")
.build();
ctx.writeAndFlush(request);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
logger.log(Level.INFO, "AuthClientInitHandler channelRead");
Auth.AuthResponse response=(Auth.AuthResponse)msg;
System.out.println("response: code="+response.getResultCode()+", message="+response.getResultMessage());
//ctx.close();
}
}
相关推荐
Netty:它使 NIO 编程更加容易,屏蔽了 Java 底层的 NIO 细节。 Protostuff:它基于 Protobuf 序列化框架,面向 POJO,无需编写 .proto 文件。 ZooKeeper:提供服务注册与发现功能,开发分布式系统的必备选择,同时...
07_Netty的Socket编程详解;08_Netty多客户端连接与通信,09_Netty读写检测机制与长连接要素,10_Netty对WebSocket的支援;11_Netty实现服务器端与客户端的长连接通信;12_Google Protobuf详解;13_定义Protobuf文件...
1、netty宏观理解 2、netty的scoket编程详解 3、netty多客户端连接与通信 4、netty读写检测机制与长连接要素 5、protobuf多协议消息支援与工程最佳实践 6、grpc通信示例与数据通信详解 .........
7_Netty的Socket编程详解 8_Netty多客户端连接与通信 9_Netty读写检测机制与长连接要素 10_Netty对WebSocket的支援 11_Netty实现服务器端与客户端的长连接通信 12_Google Protobuf详解 13_定义Protobuf文件及消息...
第7讲:Netty的Socket编程详解 第8讲:Netty多客户端连接与通信 第9讲:Netty读写检测机制与长连接要素 第10讲:Netty对WebSocket的支援 第11讲:Netty实现服务器端与客户端的长连接通信 第12讲:Google ...
scrat4nuts-netty-household-... 基于Netty、Protobuf、WebSocket的直播聊天服务器、基于Spring Web的网页服务器 https://gitee.com/chenzhenguo/NebulaMOOC?_from=gitee_search // chenzhenguo-NebulaMOOC-master
无锁异步化、事件驱动架构设计的 java netty 网络编程框架; 轻量级,无需依赖任何第三方中间件或数据库就能支持集群、分布式; 适用于网络游戏服务器、物联网、内部系统及各种需要长连接的场景; 通过 ioGame 你...
网络编程分享 -> 最小资源分1分,以下是详细章节内容,欢迎评价和收藏 章节内容: ...第21章j ava多线程编程在netty中的应用 第22章 高性能之道 第23章 可靠性 第24章 安全性 第25章 Netty未来展望
7_Netty的Socket编程详解 8_Netty多客户端连接与通信 9_Netty读写检测机制与长连接要素 10_Netty对WebSocket的支援 11_Netty实现服务器端与客户端的长连接通信 12_Google Protobuf详解 13_定义Protobuf文件及消息...
第21 章 Java 多线程编程在Netty 中的应用...... 461 第22 章 高性能之道...... 480 第23 章 可靠性...... 498 第24 章 安全性...... 522 第25 章 Netty 未来展望...... 551
约会NIO高效并发框架——Netty,需要用到Java的基础知识(多线程,网络编程,IO,设计模式尤其是代理模式),介绍了Netty的高级架构设计和核心模块组件,Google上的Protobuf作为编码解码的数据存储格式,Netty编码器...
jdk bio,nio,aio各种使用案例,深入理解netty,结合源码以及文章分析: jdk原生nio的缓冲区使用 jdk原生的nio channel使用 jdk原生的nio网络编程 jdk原生的React器编程模型(使用选择器)聊天室 零拷贝使用案例...
8)Netty中的多线程编程 9)Netty与RPC 10)Netty的可靠性 Reactor模型:基于事件驱动,适合处理海量I/O事件 1)单线程模型,所有的IO操作都在一个NIO线程上完成 存在性能和可靠性上的问题 2)多线程模型,有...
protobuf定义了一个结构化的消息格式,并提供了一组工具来生成各种编程语言的代码,使得应用程序可以轻松地创建和解析protobuf消息。同时,protobuf还支持消息的压缩和加密,以及版本兼容和升级等特性,使其在分布式...
Netty:它使 NIO 编程更加容易,屏蔽了 Java 底层的 NIO 细节。 Protostuff:它基于 Protobuf 序列化框架,面向 POJO,无需编写 .proto 文件。 ZooKeeper:提供服务注册与发现功能,开发分布式系统的必备选择,同时...
《Linux多线程服务端编程:使用muduo C++网络库》主要讲述采用现代C++在x86-64 Linux上编写多线程TCP网络服务程序的主流常规技术,重点讲解一种适应性较强的多线程服务器的编程模型,即one loop per thread。...