Почему netty не отправляет мой собственный POJO по сети?

Я пытаюсь отправить POJO "SecureMessageServerClientMessage" по сети клиенту. Оба созданы с помощью netty-Framework для Async. Сокетные коммуникации. Я действительно новичок в netty, поэтому я беру пример кода и хочу изменить его, чтобы он отправлял мой POJO по сети. Я знаю, что это много кода, но это почти пример из них, но он не работает.. Было бы очень хорошо, если бы кто-то мог сказать, почему он не работает..

Вот мои занятия: Сервер Main:

public final class SecureChatServer {

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

public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}

SecureChatServerHandler:

public class SecureChatServerHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private ArrayList<SecureMessageServerUser> userList = new ArrayList();

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        // Once session is secured, send a greeting and register the channel to the global channel
        // list so the channel received the messages from others.
        ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
                new GenericFutureListener<Future<Channel>>() {
                    @Override
                    public void operationComplete(Future<Channel> future) throws Exception {
                        channels.add(ctx.channel());
                    }
        });
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg ) throws Exception {
        System.out.println("Nachricht empfangen!");
        System.out.println("Typ: "+msg.getType());
    //Send the received message to all channels but the current one.
        for (Channel c: channels) {
            if (c != ctx.channel()) {
                c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
            } else {
                c.writeAndFlush("[you] " + msg + '\n');
            }
    }
 }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

Инициализатор (Сервер):

public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel> {

    private final SslContext sslCtx;

    public SecureChatServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // Add SSL handler first to encrypt and decrypt everything.
        // In this example, we use a bogus certificate in the server side
        // and accept any invalid certificates in the client side.
        // You will need something more complicated to identify both
        // and server in the real world.
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));

        // On top of the SSL handler, add the text line codec.
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
        pipeline.addLast(new ObjectEncoder());

        // and then business logic.
        pipeline.addLast(new SecureChatServerHandler());
    }
}

Вот код моего клиента:

public final class SecureChatClient {

    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));

            // Start the connection attempt.
            Channel ch = b.connect(HOST, PORT).sync().channel();

            // Read commands from the stdin.
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                if("send".equals(line)){
                    System.out.println("Test");
                    lastWriteFuture = ch.writeAndFlush(new SecureMessageServerClientMessage(1, "test"));
                if(lastWriteFuture.isSuccess()){
                    System.out.println("Success");
                }
                }


                // Sends the received line to the server.
                //lastWriteFuture = ch.writeAndFlush(line + "\r\n");
                // If user typed the 'bye' command, wait until the server closes
                // the connection.
                if ("bye".equals(line.toLowerCase())) {
                    ch.closeFuture().sync();
                    break;
                }
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            // The connection is closed automatically on shutdown.
            group.shutdownGracefully();
        }
    }
}

И вот обработчик:

public class SecureChatClientHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg) throws Exception {
        System.err.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

И наконец мой POJO:

public class SecureMessageServerClientMessage implements Serializable{

    private String message;
    private int type;
    static final int LISTUSER = 0, MESSAGE = 1, LOGOUT = 2, LOGIN = 3;
    private String sender;
    private String empfaenger;
    private ArrayList<SecureMessageServerUser> userList = new ArrayList();


    //Erste MSG, Login am Server
    public SecureMessageServerClientMessage(int type, String sender){
        this.type=type;
        this.sender=sender;
    }

    //Nur für den Clienten, als Anfrage für die user-List
    public SecureMessageServerClientMessage(int type){
        this.type=type;
    }

    //Für MessageTyp 0 - LISTUSER, es wird nur die aktuelle User-Liste übertragen
    public SecureMessageServerClientMessage(int type, ArrayList userList){
        this.userList=userList;
    }

    //Für MessageTyp 1 - MESSAGE Es wird der Empfänger, und die Nachricht übertragen
    public SecureMessageServerClientMessage(int type, String message, String empfaenger, String sender){
        this.type=type;
        this.message=message;
        this.sender=sender;
        this.empfaenger=empfaenger;
    }

    //Für MessageTyp 1 - Msg, die weitergeleitet werden
    public SecureMessageServerClientMessage(int type, String message, String sender){
        this.type=type;
        this.message=message;
        this.sender=sender;
    }

    public String getMessage(){
        return this.message;
    }

    public int getType(){
        return type;
    }

    public String getSender(){
        return this.sender;
    }

    public ArrayList getList() {
        return userList;
    }

    public ArrayList getUserList() {
        return userList;
    }

    public String getEmpfaenger(){
        return this.empfaenger;
    }
}

0 ответов

Другие вопросы по тегам