gpt4 book ai didi

java - 无法使用 netty 发送对象

转载 作者:行者123 更新时间:2023-11-30 11:28:56 26 4
gpt4 key购买 nike

我已经使用了一些示例来发送和接收字符串,它们运行良好。问题是我试图调整代码(阅读 api 和示例)来发送可序列化的对象,但它们不起作用。我没有收到任何错误消息,从未调用 channel 读取方法,因此服务器永远不会收到消息。我读到它可能与某种分隔符有关,但我找不到任何相关线索

这是代码,我不会包括添加和删除的处理程序,因为它们有效

服务器初始化器

protected void initChannel(SocketChannel arg0) throws Exception {
ChannelPipeline pipeline = arg0.pipeline();
pipeline.addLast("decoder", new ObjectDecoder(null));
pipeline.addLast("encoder", new ObjectEncoder());
pipeline.addLast("handler", new ChatServerHandler());
}

channel 阅读

public void channelRead0(ChannelHandlerContext arg0, Message message)
throws Exception {
Channel incoming = arg0.channel();
System.out.println("received "+ message.getContent() + "from " + message.getSender() + "\r\n" );

}

运行服务器

public void run() throws InterruptedException{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();

try{
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChatServerInitializer());
bootstrap.bind(port).sync().channel().closeFuture().sync();

}

这是客户端

protected void initChannel(SocketChannel arg0) throws Exception {
ChannelPipeline pipeline = arg0.pipeline();


pipeline.addLast("decoder", new ObjectDecoder(null));
pipeline.addLast("encoder", new ObjectEncoder());
pipeline.addLast("handler", new ChatClientHandler());

}

和主(服务器说客户端连接)

public void run(){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChatClientInitializer());

Channel channel = bootstrap.connect(host,port).sync().channel();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Message message = new Message();
message.setReceiver("user");
message.setSender("user 2");
try {
message.setContent(in.readLine());

channel.write(message);

System.out.println("Sent " + System.currentTimeMillis());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最后,没有get/set的消息类

public class Message implements Serializable {

private static final long serialVersionUID = 1L;
private String sender;
private String receiver;
private String content;
public Message(String sender, String receiver, String content){
this.setSender(sender);
this.setReceiver(receiver);
this.setContent(content);
}

非常感谢您的宝贵时间

最佳答案

检查从写操作返回的 ChannelFuture。我敢打赌它失败了。

关于java - 无法使用 netty 发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18702005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com