`
liyonghui160com
  • 浏览: 771835 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Netty+Protobuf编程

阅读更多

 

 

版本: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(10240404));
					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(10240404));
					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+protobuf (整合源代码)

    总的来说,这个项目展示了如何利用 Netty 的高性能网络编程能力,配合 Protobuf 的高效序列化特性,实现一个聊天应用。这涉及到网络编程、序列化、事件驱动编程等多个重要知识点,对于深入理解这两项技术的结合使用...

    Netty4+ProtoBuf通信框架

    总的来说,Netty4+ProtoBuf通信框架结合了Netty的网络编程能力与ProtoBuf的数据序列化效率,提供了一种高效、可靠的客户端和服务端通信解决方案。对于Java开发者来说,理解并掌握这种框架有助于开发高性能的网络应用...

    netty+protobuf入门案例

    Netty 提供了对 Protobuf 的支持,我们可以使用 Protobuf 的 `.proto` 文件生成相应的 Java 类,然后在 Netty 中处理这些类。以下是一般步骤: 1. **定义 Protobuf 消息**:创建一个 `.proto` 文件,定义消息结构。...

    通信与协议Netty+Protobuf-游戏设计与开发(1)配套代码

    本资源主要关注的是利用Netty框架和Protocol Buffers(Protobuf)进行网络通信,这在游戏开发中是一种常见的高性能解决方案。 Netty是一个Java开源框架,它提供了一个异步事件驱动的网络应用程序框架,用于快速开发...

    netty+protobuf入门案例.

    Netty和Protobuf是两种在IT领域中广泛使用的开源技术,尤其在开发高效、高性能的网络应用程序时。本文将深入探讨这两个技术,并结合一个入门案例,帮助初学者理解如何将它们结合起来使用。 Netty是一个高性能、异步...

    springboot集成netty,使用protobuf作为数据交换格式,可以用于智能终端云端服务脚手架

    protobuf 提供了语言无关、平台无关的接口,可以在不同的编程语言之间无缝交换数据。相比传统的JSON或XML,protobuf序列化的数据更小、解析速度更快,非常适合用于性能敏感的应用场景。 在本项目中,protobuf 被...

    采用netty与protobuf进行文件传输

    本话题聚焦于使用Netty和Protocol Buffers(Protobuf)来实现文件传输,这是一种现代且高性能的技术组合,尤其适用于大规模分布式系统。 Netty是一个开源的异步事件驱动的网络应用程序框架,用于快速开发可维护的高...

    毕设项目:基于netty+websocket+springboot的实时聊天系统.zip

    这是一个基于Netty、WebSocket和Spring Boot技术实现的实时...通过实践这个项目,开发者可以深入理解Spring Boot的自动化配置、Netty的网络编程模型以及WebSocket在实时通信中的应用,同时也能锻炼前后端协作的能力。

    cdeer-im, 基于Netty+Redis+protobuf开发的即时通讯服务器.zip

    通过使用Channel、EventLoopGroup、ByteBuf等组件,Netty提供了高度灵活和可扩展的网络编程接口,使得开发者可以专注于业务逻辑,而无需关注底层网络通信的复杂性。 **Redis简介** Redis是一个开源的键值存储系统...

    Netty中Protobuf编解码应用

    开发者可以使用protobuf编译器将.proto文件转换为各种编程语言的源代码,这些源代码提供了序列化和反序列化的方法。在Java中,生成的类提供了`toByteArray()`和`parseFrom(byte[])`等API,用于数据的编码和解码。 ...

    netty+thrift高并发高性能

    - **序列化码流过大**:Java序列化的码流相比其他轻量级序列化框架(如Thrift、Protobuf等)体积较大,增加了网络传输的负担。 - **序列化性能低**:Java序列化的CPU开销相对较高,尤其是在大规模数据处理时会影响...

    netty http protobuf

    Netty、HTTP与Protobuf是三个在IT领域中至关重要的技术组件,它们分别在不同的层面上为高性能网络应用提供服务。下面将详细解释这三个概念及其相互结合的应用。 **Netty** Netty是一个开源的Java NIO(非阻塞I/O)...

    基于netty和protobuf的聊天系统,客户端+服务器

    此外,Netty还提供了丰富的API和强大的功能,如线程池管理、心跳检测、数据编码解码等,极大地简化了网络编程的复杂性。 Protocol Buffers(protobuf)是Google开发的一种数据序列化协议,它提供了一种高效、跨平台...

    一个基于Nacos、Netty、Protobuf 实现的简单易懂的RCP框架.zip

    标题中的“一个基于Nacos、Netty、Protobuf 实现的简单易懂的RCP框架”指的是一个使用了阿里巴巴的Nacos服务发现平台、高性能的网络库Netty以及高效的序列化协议Protobuf来构建的远程过程调用(RPC)框架。...

    android netty cli +probuf示例

    在Android平台上实现即时通讯功能,Netty和Protobuf(Protocol Buffers)的结合是一个高效、可靠的解决方案。本文将深入探讨如何使用这两个技术构建一个客户端应用程序。 Netty是Java领域的一款高性能、异步事件...

    使用Netty+Protocol Buffer实现聊天室

    在构建一个基于Android的聊天室应用时,使用Netty和Protocol Buffers(protobuf)是一种高效且灵活的方法。本文将深入探讨这两个技术如何协同工作,以及它们在实现聊天室功能中的关键作用。 首先,让我们理解一下...

    spring boot +maven+ netty4+protostuff+zookeeper实现一个轻量级RPC框架

    Netty:它使 NIO 编程更加容易,屏蔽了 Java 底层的 NIO 细节。 Protostuff:它基于 Protobuf 序列化框架,面向 POJO,无需编写 .proto 文件。 ZooKeeper:提供服务注册与发现功能,开发分布式系统的必备选择,同时...

    一个基于Java的开源游戏服务器框架实现,使用了Netty、ProtoBuf、Disruptor等.zip

    在这个特定的项目中,一个基于Java的开源游戏服务器框架被实现,利用了几个关键的技术栈,包括Netty、ProtoBuf和Disruptor。这些技术都是为了优化性能、提高效率和简化通信而设计的。 Netty是一个高性能、异步事件...

    Netty Protobuf3 测试服务器

    在这个“Netty Protobuf3 测试服务器”项目中,开发者使用Netty框架来构建一个服务器,该服务器与Unity游戏引擎中的protobuf3(Protocol Buffers版本3)进行通信。protobuf3是Google开发的一种数据序列化协议,它...

Global site tag (gtag.js) - Google Analytics