2

首先感谢您花时间阅读本文。

我目前遇到了一个非常奇怪的错误。我对 java 有点熟悉,但对 Netty 很陌生。我正在编写一个类似于示例中的 SecureChat 的聊天程序。

我的问题是:我能够启动服务器。服务器绑定到正确的地址,没有错误。但是当我启动客户端时,它连接到服务器等待几秒钟并终止,没有控制台输出指示错误的类型。通道似乎已建立并处于活动状态,至少调用了相应的方法。当 Channel/Connection 处于活动状态时,服务器应该发送一个问候包。客户端未收到此问候数据包。或者至少看起来不是。
聊天服务器.java:

package main;

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

public class ChatServer {

private final int port;

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

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception     {
                ch.pipeline().addLast(
                    new ObjectEncoder(),
                    new     ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                    new ChatServerHandler());   
            }
        });
        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

    }
}

public static void main(String[] args) throws Exception {
    int port;
    if (args.length > 0){
        port = Integer.parseInt(args[0]);
    } else {
        port = 3000;
    }
    new ChatServer(port).run();
}

}


ChatServerHandler.java:

package main;

import java.util.logging.Level;
import java.util.logging.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import net.Packet;
import net.server.ChannelIntercommunicationHandler;
import net.server.PacketGreetings;

public class ChatServerHandler extends ChannelInboundMessageHandlerAdapter<Packet>{

private static final Logger logger = Logger.getLogger(ChatServerHandler.class.getName());

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception{
    ctx.write(new PacketGreetings("Hello! Welcome in Chat. Please log in"));
    ChannelIntercommunicationHandler.addChannel(ctx.channel());
    logger.log(Level.INFO, "Sent greetings packet to User with ChannelID: "+ctx.channel().id());
}

@Override
public void messageReceived(ChannelHandlerContext ctx, Packet request) throws Exception {
    ChannelIntercommunicationHandler.packetReceived(ctx.channel(), request);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    System.out.println("Error, Exiting.");
    logger.log(Level.WARNING, "Unexpected exception from downstream.", cause);
    ChannelIntercommunicationHandler.cleanupChannel(ctx.channel());
    ctx.close();
}

}


聊天客户端.java

package main;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
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 ChatClient implements Runnable{
private final String host;
private final int port;

public ChatClient(String host, int port){
    this.host = host;
    this.port = port;
}

@Override
public void run() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast(
                         new ObjectEncoder(),
                         new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                         new ChatClientHandler());
             }
         });
        b.connect(host, port).sync().channel().closeFuture().sync();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}

public static void main(String[] args) throws Exception {
    new ChatClient("localhost", 3000).run();
}

}


ChatClientHandler.java:

package main;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

import java.util.logging.Level;
import java.util.logging.Logger;

import net.Packet;
import net.client.ClientPacketHandler;
import net.client.PacketLoginCredentials;

public class ChatClientHandler extends ChannelInboundMessageHandlerAdapter<Packet>{
 private static final Logger logger =     Logger.getLogger(ChatClientHandler.class.getName());

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    logger.log(Level.INFO, "Channel Active with with ChannelID: "+ctx.channel().id());
    ctx.write(new PacketLoginCredentials("martin", "123456"));
}

@Override
public void messageReceived(ChannelHandlerContext ctx, Packet p) throws Exception{
    logger.log(Level.INFO, "messageReceived with ClassEntity: "+p.getClass().getName());
    ClientPacketHandler.packetReceived(p, ctx.channel());
}
}

我也已经尝试过远程登录服务器。连接立即建立并关闭。我猜它是一个服务器问题。

我正在寻找错误 2 天,但找不到它。

任何帮助表示赞赏

谢谢

4

0 回答 0