Netty 使用JsonString 传递POJO

创建一个回应客户端信息的ServerPojoHandler

package com.demo.pojo.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

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 {
		JSONObject jo = JSON.parseObject(msg.toString());
		String message = JSONObject.toJSONString(jo);
		System.out.println("ServerHandler rec:"+message);
		ctx.writeAndFlush(message);
		System.out.println("ServerHandler send:"+message);
	}
}

创建一个操作控制端信息的 ClientPojoHandler

package com.demo.pojo.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

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 {
		JSONObject jo = JSON.parseObject(msg.toString());
		System.out.println("ClientHandler rec- name:"+jo.getString("name"));
		System.out.println("ClientHandler rec- age:"+jo.getString("age"));
		System.out.println("ClientHandler rec- sex:"+jo.getString("sex"));
		System.out.println("ClientHandler rec- Experience:"+jo.getString("Experience"));
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		
		JSONObject jo = new JSONObject();
		jo.put("name", "MaYun");
		jo.put("age", "100");
		jo.put("sex", "man");
		JSONArray ja = new JSONArray();
		ja.add("Teacher");
		ja.add("Entrepreneur");
		ja.add("Boss");
		jo.put("Experience", ja);
		String message = JSONObject.toJSONString(jo);
		ctx.writeAndFlush(message);
		System.out.println("Client send :"+message);
	}
}

创建一个Server

package com.demo.pojo.server;

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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

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 StringEncoder());
						pipeline.addLast(new StringDecoder());
						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.pojo.client;

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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

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 StringEncoder());
						pipeline.addLast(new StringDecoder());
						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
ServerHandler rec:{"Experience":["Teacher","Entrepreneur","Boss"],"sex":"man","name":"MaYun","age":"100"}
ServerHandler send:{"Experience":["Teacher","Entrepreneur","Boss"],"sex":"man","name":"MaYun","age":"100"}

客户端运行结果

连接服务器成功: 8080
Client send :{"Experience":["Teacher","Entrepreneur","Boss"],"sex":"man","name":"MaYun","age":"100"}
ClientHandler rec- name:MaYun
ClientHandler rec- age:100
ClientHandler rec- sex:man
ClientHandler rec- Experience:["Teacher","Entrepreneur","Boss"]
posted @   8848-自律即自由  阅读(315)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示