Netty 使用序列化传递POJO

Netty使用序列化传递POJO

创建一个用来传递的对象,实现序列化

package com.demo.dto;

import java.io.Serializable;

public class Demo implements Serializable{
	
	/**
	 * Demo serialVersionUID
	 */
	private static final long serialVersionUID = 102834737437409437L;
	
	/**
	 * 数据包类型
	 */
	public String Types;
	/**
	 * 消息
	 */
	public String Message;
	
	
	public String getTypes() {
		return Types;
	}
	public void setTypes(String types) {
		Types = types;
	}
	public String getMessage() {
		return Message;
	}
	public void setMessage(String message) {
		Message = message;
	}
	
	@Override
	public String toString() {
		return "Demo [Types=" + Types + ", Message=" + Message + "]";
	}
	
}

创建一个ServerPojoHandler 用来接收客户端传递的对象并回传给客户端

package com.demo.handler;

import com.demo.dto.Demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerPojoHandler extends ChannelInboundHandlerAdapter {
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Demo byteBuf = (Demo)msg;
		System.out.println("ServerHandler rec:"+byteBuf.toString());
		byteBuf.Message = "Server Message";
		byteBuf.Types = "Server";
		ctx.writeAndFlush(byteBuf);
		System.out.println("ServerHandler send:"+byteBuf.toString());
	}

}

创建一个ClientPojoHandler 用来发送对象到服务端,并接受服务端回传的对象

package com.demo.handler;

import com.demo.dto.Demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientPojoHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Demo byteBuf = (Demo) msg;
		System.out.println("ClientHandler rec:"+byteBuf.toString());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		Demo demo = new Demo();
		demo.Message = "Client Message";
		demo.Types = "Client";
		ctx.writeAndFlush(demo);
		System.out.println("Client send :"+demo.toString());
	}

}

创建一个服务端Server

package com.demo.server;

import com.demo.handler.ServerPojoHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class Server {

	private static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));

	public static void main(String[] args) throws InterruptedException {
		ServerBootstrap bootstrap = new ServerBootstrap();

		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();

		bootstrap.group(boss, worker)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.option(ChannelOption.TCP_NODELAY, true)
				.childHandler(new ChannelInitializer<NioSocketChannel>() {
					@Override
					protected void initChannel(NioSocketChannel channel) throws Exception {
						ChannelPipeline pipeline = channel.pipeline();
						pipeline.addLast(new ObjectEncoder());
						pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
	                            ClassResolvers.cacheDisabled(null)));
						pipeline.addLast(new ServerPojoHandler());
					}
				});

		ChannelFuture future = bootstrap.bind(PORT).sync();
		if (future.isSuccess()) {
			System.out.println("端口绑定成功"+PORT);
		} else {
			System.out.println("端口绑定失败"+PORT);
		}

		future.channel().closeFuture().sync();
	}
}

创建一个客户端Client

package com.demo.client;

import com.demo.handler.ClientPojoHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class Client {

	private static final String HOST = System.getProperty("host", "127.0.0.1");

	private static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));

	public static void main(String[] args) throws InterruptedException {

		Bootstrap bootstrap = new Bootstrap();

		NioEventLoopGroup group = new NioEventLoopGroup();

		bootstrap.group(group)
				.channel(NioSocketChannel.class)
				.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
				.option(ChannelOption.SO_KEEPALIVE, true)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<NioSocketChannel>() {
					@Override
					protected void initChannel(NioSocketChannel channel) throws Exception {
						ChannelPipeline pipeline = channel.pipeline();
						pipeline.addLast(new ObjectEncoder());
						pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
	                            ClassResolvers.cacheDisabled(null)));
						pipeline.addLast(new ClientPojoHandler());
					}
				});

		ChannelFuture future = bootstrap.connect(HOST, PORT).sync();
		if (future.isSuccess()) {
			System.out.println("连接服务器成功"+PORT);
		} else {
			System.out.println("连接服务器失败"+PORT);
		}

		future.channel().closeFuture().sync();
	}
}

运行的客户端日志

连接服务器成功8080
Client send :Demo [Types=Client, Message=Client Message]
ClientHandler rec:Demo [Types=Server, Message=Server Message]

运行的服务端消息

端口绑定成功8080
ServerHandler rec:Demo [Types=Client, Message=Client Message]
ServerHandler send:Demo [Types=Server, Message=Server Message]
posted @   8848-自律即自由  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示