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"]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南