netty4 tcp与protobuf3的整合使用。

7 篇文章 1 订阅


netty是一个非常棒的NIO框架就不介绍了。protobuf是google提供的一个开源序列化框架,也是一个非常棒的东西。这里不介绍这两个框架了,想要了解的朋友网上一搜一大把。


本文主要介绍 protobuf3与netty4 在tcp协议里的整合使用。个人认为netty与protobuf是绝配的组合。配合使用非常棒,框架提供了粘包拆包等工具类。特别是你要实现如及时通讯功能的时候,能让你省很多功夫。


使用protobuf需要事先预编译,这个过程这里就不介绍了,我的博客里面有,需要的可以看看。


首先在java中使用netty与protobuf需要两个jar包,我这里是:netty-all-4.1.0.CR7.jar、protobuf-java-3.1.0.jar(可以到maven下载,版本可以不同)


直接来看看代码吧。都有详细的注释:


package com.im.socket.netty.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentMap;

import org.jboss.netty.util.internal.ConcurrentHashMap;

/**
 * 建立TCP netty服务
 * 
 * @author kokJuis
 * @version 1.0
 * @date 2016-9-30
 */
public class ChatServer {

	// 实例一个连接容器保存连接
	public static ChannelGroup channels = new DefaultChannelGroup(
			GlobalEventExecutor.INSTANCE);

	// 再搞个map保存与用户的映射关系
	public static ConcurrentMap<Integer, ChannelId> userSocketMap = new ConcurrentHashMap<Integer, ChannelId>();

	private int port;

	public ChatServer(int port) {
		this.port = port;
	}

	public void run() throws Exception {

		EventLoopGroup bossGroup = new NioEventLoopGroup();// boss线程池
		EventLoopGroup workerGroup = new NioEventLoopGroup();// worker线程池
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)// 使用TCP
					.childHandler(new ChatServerInitializer())// 初始化配置的处理器
					.option(ChannelOption.SO_BACKLOG, 128)// BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。
					.childOption(ChannelOption.SO_KEEPALIVE, true);// 是否启用心跳保活机制。在双方TCP套接字建立连接后(即都进入ESTABLISHED状态)并且在两个小时左右上层没有任何数据传输的情况下,这套机制才会被激活。

			System.out.println("[ChatServer 启动了]");

			// 绑定端口,开始接收进来的连接
			ChannelFuture f = b.bind(port).sync();

			// 等待服务器 socket 关闭 。
			// 这不会发生,可以优雅地关闭服务器。
			f.channel().closeFuture().sync();

		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();

			System.out.println("[ChatServer 关闭了]");
		}
	}

}


package com.im.socket.netty.tcp;

import java.util.concurrent.TimeUnit;

import com.im.socket.protobuf.MessageOuterClass.Message;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;

/**
 * netty处理器配置
 * 
 * @author kokJuis
 * @version 1.0
 * @date 2016-9-30
 */
public class ChatServerInitializer extends ChannelInitializer<SocketChannel> {

	Timer timer;

	public ChatServerInitializer() {
		timer = new HashedWheelTimer();
	}

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();

		// ----Protobuf处理器,这里的配置是关键----
		pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());// 用于decode前解决半包和粘包问题(利用包头中的包含数组长度来识别半包粘包)
		//配置Protobuf解码处理器,消息接收到了就会自动解码,ProtobufDecoder是netty自带的,Message是自己定义的Protobuf类
		pipeline.addLast("protobufDecoder",
				new ProtobufDecoder(Message.getDefaultInstance()));
		// 用于在序列化的字节数组前加上一个简单的包头,只包含序列化的字节长度。
		pipeline.addLast("frameEncoder",
				new ProtobufVarint32LengthFieldPrepender());
		//配置Protobuf编码器,发送的消息会先经过编码
		pipeline.addLast("protobufEncoder", new ProtobufEncoder());
		// ----Protobuf处理器END----

		pipeline.addLast("handler", new ChatServerHandler());//自己定义的消息处理器,接收消息会在这个类处理
		pipeline.addLast("ackHandler", new AckServerHandler());//处理ACK
		pipeline.addLast("timeout", new IdleStateHandler(100, 0, 0,
				TimeUnit.SECONDS));// //此两项为添加心跳机制,60秒查看一次在线的客户端channel是否空闲
		pipeline.addLast(new HeartBeatServerHandler());// 心跳处理handler

	}

	// pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
	// 2 * 1024, Delimiters.lineDelimiter()));
	// pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
	// pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
}

package com.im.socket.netty.tcp;

import java.util.Map.Entry;

import com.im.socket.enums.EnumMessageType;
import com.im.socket.protobuf.MessageOuterClass.Message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 消息处理类
 * 
 * @author kokJuis
 * @version 1.0
 * @date 2016-9-30
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<Message> {

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel incoming = ctx.channel();
		System.out.println("[SERVER] - " + incoming.remoteAddress() + " 连接过来\n");
		
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel incoming = ctx.channel();
		ChatServer.channels.remove(incoming);

		System.out.println("[SERVER] - " + incoming.remoteAddress() + " 离开\n");

		// A closed Channel is automatically removed from ChannelGroup,
		// so there is no need to do "channels.remove(ctx.channel());"
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Message msg)
			throws Exception {
		
		
		//消息会在这个方法接收到,msg就是经过解码器解码后得到的消息,框架自动帮你做好了粘包拆包和解码的工作
		
		//处理消息逻辑
		
		ctx.fireChannelRead(msg);//把消息交给下一个处理器
		

	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
		Channel incoming = ctx.channel();
		System.out.println("ChatClient:" + incoming.remoteAddress() + "上线");

	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
		Channel incoming = ctx.channel();
		System.out.println("ChatClient:" + incoming.remoteAddress() + "掉线");


	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
		Channel incoming = ctx.channel();
		// 当出现异常就关闭连接
		System.out.println("ChatClient:" + incoming.remoteAddress()
				+ "异常,已被服务器关闭");
		cause.printStackTrace();
		
		ctx.close();
	}

}

package com.im.socket.netty.tcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 心跳检测
 * 
 * @ClassName HeartBeatServerHandler
 * @Description TODO
 * @author kokjuis 189155278@qq.com
 * @date 2016-9-26
 * @content
 */
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

	private int loss_connect_time = 0;

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE) {
				loss_connect_time++;
				System.out.println("[60 秒没有接收到客户端" + ctx.channel().id()
						+ "的信息了]");
				if (loss_connect_time > 2) {
					// 超过20秒没有心跳就关闭这个连接
					System.out.println("[关闭这个不活跃的channel:" + ctx.channel().id()
							+ "]");
					ctx.channel().close();
				}
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

}



  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: Spring Boot可以很方便地整合Netty实现TCP协议的通信。具体实现步骤如下: 1. 引入Netty依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> ``` 2. 编写Netty服务端 编写一个Netty服务端,监听指定端口,接收客户端的请求,并返回响应。具体实现可以参考Netty官方文档。 3. 配置Spring Boot 在Spring Boot的配置文件中,配置Netty服务端的端口号和其他相关参数。 4. 启动Spring Boot应用程序 启动Spring Boot应用程序,Netty服务端会自动启动并监听指定端口。 5. 编写客户端程序 编写一个客户端程序,连接Netty服务端,并发送请求。具体实现可以参考Netty官方文档。 通过以上步骤,就可以实现Spring Boot整合Netty实现TCP协议的通信。 ### 回答2: Spring Boot是一个非常流行的Java开源框架,它提供了一种简单且快捷的方式来构建可扩展的Web应用程序。而Netty是一个基于NIO的客户端/服务器框架,它可以轻松处理高负载的网络通信。 因此通过Spring Boot和Netty整合,可以实现高效,快速,可扩展的TCP通信,在需要高性能可扩展的应用程序中是有很大的优势的。 实现过程如下: 1. 通过Spring Boot创建一个Maven项目,引入Netty依赖。 2. 创建Netty服务端和客户端,用于实现TCP通讯。服务端可以监听端口,客户端则可以连接服务端。 3. 将Netty的ChannelHandler封装成Spring Bean,并在Spring Boot中进行注入。 4. 通过使用Spring Boot的自动配置功能,将服务端和客户端的配置信息进行注入,从而使整个过程的配置更加简单。 5. 为了更好地支持多个客户端并发操作,可以使用Netty的线程池功能来提高性能和稳定性。 6. 配置Spring Boot,使其运行在指定的端口,并且注册Netty ChannelHandler,使其能够接收和处理来自客户端的请求消息。 7. 编写客户端代码,建立与服务端的连接并发送数据。 8. 客户端与服务端完成通信后,可以将数据响应给客户端,并断开连接。 通过以上步骤,就可以使用Spring Boot和Netty实现高效,快速,可扩展的TCP通信。这种架构有很多优点,例如高并发,高性能,易于维护,容易扩展等。对于需要实现实时数据传输和高性能的应用程序而言,这是一种非常好的解决方案。 ### 回答3: Springboot是一款非常流行的Java开发框架,它提供了很多便捷的工具和库,帮助开发者更快地搭建高效的应用程序。Netty则是一款基于NIO的高性能网络通信框架,非常适合开发高并发、高性能的网络应用。 利用Springboot整合Netty实现TCP通信可以方便地实现异步、非阻塞IO,而不需要开发者手动处理Java NIO的细节。下面简要介绍如何利用Springboot整合Netty实现TCP通信。 1. 引入Netty的依赖 在pom.xml文件中引入Netty的依赖,例如: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> ``` 2. 实现Netty服务端 创建一个NettyServer类,继承自ChannelInboundHandlerAdapter,并实现以下方法: ``` public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {} public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {} public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {} ``` 在NettyServer类的构造方法中启动Netty服务端,示例代码如下: ``` public class NettyServer extends ChannelInboundHandlerAdapter { public NettyServer() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServer()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理读事件 } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // 读事件完成处理 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 处理异常 } // 启动Netty服务端 public static void main(String[] args) { new NettyServer(); } } ``` 3. 实现Netty客户端 创建一个NettyClient类,继承自SimpleChannelInboundHandler,并实现以下方法: ``` public void channelActive(ChannelHandlerContext ctx) throws Exception {} protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {} public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {} ``` 在NettyClient类的构造方法中启动Netty客户端,示例如下: ``` public class NettyClient extends SimpleChannelInboundHandler<String> { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$_".getBytes()))); ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new NettyClient(host, port)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // 发送消息 } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // 处理读事件 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 处理异常 } // 启动Netty客户端 public static void main(String[] args) { String host = "127.0.0.1"; int port = 8080; new NettyClient(host, port); } } ``` 以上是利用Springboot整合Netty实现TCP通信的大致步骤。实际开发过程中还需要根据应用程序的具体需求进一步优化和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值