Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带POJO的耐特乒乓球_Java_Io_Client Server_Netty_Nio - Fatal编程技术网

Java 带POJO的耐特乒乓球

Java 带POJO的耐特乒乓球,java,io,client-server,netty,nio,Java,Io,Client Server,Netty,Nio,为什么客户端不接收服务器发送的POJO 这对我来说有点难理解 我意识到这需要很多代码,但我不知道如何在客户端和服务器之间使用POJO(在本例中为Quote)的同时将其精简。服务器在建立连接时发送报价: run: [java] Aug 03, 2014 5:32:20 PM net.bounceme.dur.netty.QuoteServerInitializer <init> [java] INFO: ..initializing.. [java] Au

为什么客户端不接收服务器发送的POJO

这对我来说有点难理解

我意识到这需要很多代码,但我不知道如何在客户端和服务器之间使用POJO(在本例中为
Quote
)的同时将其精简。服务器在建立连接时发送报价:

run:
     [java] Aug 03, 2014 5:32:20 PM net.bounceme.dur.netty.QuoteServerInitializer <init>
     [java] INFO: ..initializing..
     [java] Aug 03, 2014 5:32:23 PM net.bounceme.dur.netty.QuoteServerInitializer initChannel
     [java] INFO: ..adding to pipeline..
     [java] Aug 03, 2014 5:32:23 PM net.bounceme.dur.netty.QuoteServerHandler <init>
     [java] INFO: ..started..
     [java] Aug 03, 2014 5:32:23 PM net.bounceme.dur.netty.QuoteServerHandler channelActive
     [java] INFO: ..sending new server Quote..
     [java] Aug 03, 2014 5:32:23 PM net.bounceme.dur.netty.QuoteEncoder encode
     [java] INFO: 
     [java] 
     [java] id      0
     [java] quote   Where there is love there is life.
^Cthufir@dur:~/NetBeansProjects/QuoteServer$ 
thufir@dur:~/NetBeansProjects/QuoteServer$ ^C
thufir@dur:~/NetBeansProjects/QuoteServer$ 
服务器初始值设定项: 包net.bounceme.dur.netty

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteServerInitializer.class.getName());

    public QuoteServerInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("..adding to pipeline..");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteServerHandler());
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteServerHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteServerHandler.class.getName());
    private static final Random random = new Random();

    public QuoteServerHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static Quote nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return new Quote(quotes[quoteId]);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new server Quote..");
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(nextQuote());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import java.util.logging.Logger;

public final class QuoteClient {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    public static void main(String... args) throws InterruptedException, IOException {
        new QuoteClient().connect();
    }

    public void connect() throws InterruptedException, IOException {
        MyProps p = new MyProps();
        String host = p.getHost();
        int port = p.getServerPort();
        pingPong(host, port);
    }

    public void pingPong(String host, int port) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new QuoteClientInitializer());
            ChannelFuture cf = b.connect(host, port);
            cf.sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteClientInitializer.class.getName());

    public QuoteClientInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteClientHandler());
    }
}
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

@Sharable
public class QuoteClientHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new client Quote..");
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.fireChannelReadComplete();
    }

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

}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteDecoder extends MessageToMessageDecoder<Quote> {

    private static final Logger log = Logger.getLogger(QuoteDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteEncoder extends MessageToMessageEncoder<Quote> {

            private static final Logger log = Logger.getLogger(QuoteEncoder.class.getName());


    @Override
    protected void encode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
客户端初始值设定项: 包net.bounceme.dur.netty

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteServerInitializer.class.getName());

    public QuoteServerInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("..adding to pipeline..");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteServerHandler());
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteServerHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteServerHandler.class.getName());
    private static final Random random = new Random();

    public QuoteServerHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static Quote nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return new Quote(quotes[quoteId]);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new server Quote..");
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(nextQuote());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import java.util.logging.Logger;

public final class QuoteClient {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    public static void main(String... args) throws InterruptedException, IOException {
        new QuoteClient().connect();
    }

    public void connect() throws InterruptedException, IOException {
        MyProps p = new MyProps();
        String host = p.getHost();
        int port = p.getServerPort();
        pingPong(host, port);
    }

    public void pingPong(String host, int port) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new QuoteClientInitializer());
            ChannelFuture cf = b.connect(host, port);
            cf.sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteClientInitializer.class.getName());

    public QuoteClientInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteClientHandler());
    }
}
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

@Sharable
public class QuoteClientHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new client Quote..");
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.fireChannelReadComplete();
    }

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

}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteDecoder extends MessageToMessageDecoder<Quote> {

    private static final Logger log = Logger.getLogger(QuoteDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteEncoder extends MessageToMessageEncoder<Quote> {

            private static final Logger log = Logger.getLogger(QuoteEncoder.class.getName());


    @Override
    protected void encode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
导入io.netty.channel.ChannelInitializer;
导入io.netty.channel.ChannelPipeline;
导入io.netty.channel.socket.SocketChannel;
导入io.netty.handler.codec.delimiterBaseFrameDecoder;
导入io.netty.handler.codec.Delimiters;
导入java.util.logging.Logger;
公共类QuoteClientInitializer扩展了ChannelInitializer{
私有静态最终记录器log=Logger.getLogger(QuoteClientInitializer.class.getName());
公共商客户初始值设定项(){
log.info(“…初始化…”);
}
@凌驾
公共频道(SocketChannel ch){
ChannelPipeline=通道管道();
addLast(新的DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter());
addLast(新的QuotedCoder());
addLast(新的QuoteEncoder());
addLast(新的QuoteClientHandler());
}
}
客户端处理程序: 包net.bounceme.dur.netty

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteServerInitializer.class.getName());

    public QuoteServerInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("..adding to pipeline..");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteServerHandler());
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteServerHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteServerHandler.class.getName());
    private static final Random random = new Random();

    public QuoteServerHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static Quote nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return new Quote(quotes[quoteId]);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new server Quote..");
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(nextQuote());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import java.util.logging.Logger;

public final class QuoteClient {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    public static void main(String... args) throws InterruptedException, IOException {
        new QuoteClient().connect();
    }

    public void connect() throws InterruptedException, IOException {
        MyProps p = new MyProps();
        String host = p.getHost();
        int port = p.getServerPort();
        pingPong(host, port);
    }

    public void pingPong(String host, int port) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new QuoteClientInitializer());
            ChannelFuture cf = b.connect(host, port);
            cf.sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteClientInitializer.class.getName());

    public QuoteClientInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteClientHandler());
    }
}
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

@Sharable
public class QuoteClientHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new client Quote..");
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.fireChannelReadComplete();
    }

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

}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteDecoder extends MessageToMessageDecoder<Quote> {

    private static final Logger log = Logger.getLogger(QuoteDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteEncoder extends MessageToMessageEncoder<Quote> {

            private static final Logger log = Logger.getLogger(QuoteEncoder.class.getName());


    @Override
    protected void encode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
导入io.netty.channel.ChannelHandler.Sharable;
导入io.netty.channel.ChannelHandlerContext;
导入io.netty.channel.SimpleChannelInboundHandler;
导入java.util.logging.Logger;
导入net.bounceme.dur.jdbc.Quote;
@可分享
公共类QuoteClientHandler扩展了SimpleChannelInboundHandler{
私有静态最终记录器log=Logger.getLogger(QuoteClient.class.getName());
@凌驾
公共无效channelActive(ChannelHandlerContext ctx)引发异常{
log.info(“…发送新客户报价…”);
ctx.writeAndFlush(新报价(“客户”));
}
@凌驾
受保护的无效channelRead0(ChannelHandlerContext chc,Quote Quote)引发异常{
log.info(quote.toString());
}
@凌驾
public void channelRead(ChannelHandlerContext ctx,Object msg){
log.info(msg.toString());
ctx.writeAndFlush(新报价(“客户”));
}
@凌驾
公共无效channelReadComplete(ChannelHandlerContext ctx){
ctx.fireChannelReadComplete();
}
@凌驾
公共无效例外情况(ChannelHandlerContext ctx,可丢弃原因){
log.info(cause.toString());
ctx.close();
}
}
解码器: 包net.bounceme.dur.netty

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteServerInitializer.class.getName());

    public QuoteServerInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("..adding to pipeline..");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteServerHandler());
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteServerHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteServerHandler.class.getName());
    private static final Random random = new Random();

    public QuoteServerHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static Quote nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return new Quote(quotes[quoteId]);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new server Quote..");
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(nextQuote());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import java.util.logging.Logger;

public final class QuoteClient {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    public static void main(String... args) throws InterruptedException, IOException {
        new QuoteClient().connect();
    }

    public void connect() throws InterruptedException, IOException {
        MyProps p = new MyProps();
        String host = p.getHost();
        int port = p.getServerPort();
        pingPong(host, port);
    }

    public void pingPong(String host, int port) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new QuoteClientInitializer());
            ChannelFuture cf = b.connect(host, port);
            cf.sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteClientInitializer.class.getName());

    public QuoteClientInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteClientHandler());
    }
}
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

@Sharable
public class QuoteClientHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new client Quote..");
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.fireChannelReadComplete();
    }

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

}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteDecoder extends MessageToMessageDecoder<Quote> {

    private static final Logger log = Logger.getLogger(QuoteDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteEncoder extends MessageToMessageEncoder<Quote> {

            private static final Logger log = Logger.getLogger(QuoteEncoder.class.getName());


    @Override
    protected void encode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
导入io.netty.channel.ChannelHandlerContext;
导入io.netty.handler.codec.MessageToMessageDecoder;
导入java.util.List;
导入java.util.logging.Logger;
导入net.bounceme.dur.jdbc.Quote;
公共类QuotedCoder扩展MessageToMessageDecoder{
私有静态最终记录器log=Logger.getLogger(QuoteCoder.class.getName());
@凌驾
受保护的无效解码(ChannelHandlerContext chc、Quote Quote、List List)引发异常{
log.info(quote.toString());
列表。添加(报价);
}
}
编码器: 包net.bounceme.dur.netty

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteServerInitializer.class.getName());

    public QuoteServerInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("..adding to pipeline..");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteServerHandler());
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteServerHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteServerHandler.class.getName());
    private static final Random random = new Random();

    public QuoteServerHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static Quote nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return new Quote(quotes[quoteId]);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new server Quote..");
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(nextQuote());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(nextQuote());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import java.util.logging.Logger;

public final class QuoteClient {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    public static void main(String... args) throws InterruptedException, IOException {
        new QuoteClient().connect();
    }

    public void connect() throws InterruptedException, IOException {
        MyProps p = new MyProps();
        String host = p.getHost();
        int port = p.getServerPort();
        pingPong(host, port);
    }

    public void pingPong(String host, int port) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new QuoteClientInitializer());
            ChannelFuture cf = b.connect(host, port);
            cf.sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import java.util.logging.Logger;

public class QuoteClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger log = Logger.getLogger(QuoteClientInitializer.class.getName());

    public QuoteClientInitializer() {
        log.info("..initializing..");
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new QuoteDecoder());
        pipeline.addLast(new QuoteEncoder());
        pipeline.addLast(new QuoteClientHandler());
    }
}
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

@Sharable
public class QuoteClientHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(QuoteClient.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("..sending new client Quote..");
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info(msg.toString());
        ctx.writeAndFlush(new Quote("client"));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.fireChannelReadComplete();
    }

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

}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteDecoder extends MessageToMessageDecoder<Quote> {

    private static final Logger log = Logger.getLogger(QuoteDecoder.class.getName());

    @Override
    protected void decode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class QuoteEncoder extends MessageToMessageEncoder<Quote> {

            private static final Logger log = Logger.getLogger(QuoteEncoder.class.getName());


    @Override
    protected void encode(ChannelHandlerContext chc, Quote quote, List<Object> list) throws Exception {
        log.info(quote.toString());
        list.add(quote);
    }
}
导入io.netty.channel.ChannelHandlerContext;
导入io.netty.handler.codec.MessageToMessageEncoder;
导入java.util.List;
导入java.util.logging.Logger;
导入net.bounceme.dur.jdbc.Quote;
公共类QuotenCoder扩展MessageToMessageEncoder{
私有静态最终记录器log=Logger.getLogger(QuoteEncoder.class.getName());
@凌驾
受保护的无效编码(ChannelHandlerContext chc、Quote Quote、List List)引发异常{
log.info(quote.toString());
列表。添加(报价);
}
}

值得注意的是,en/de-code方法从未登录到控制台。

如果将QuoteServerHandler的
channelActive
方法编辑为以下内容:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    log.info("..sending new server Quote..");
    ChannelFuture cf = ctx.writeAndFlush(nextQuote());
    if (!cf.isSuccess()){
        log.log(Level.SEVERE, cf.toString());
    }
    ctx.fireChannelActive();
}
然后,您很可能会收到一条消息说:
不支持的消息类型:Quote

您的编码器需要将其编码为受支持的内容。我现在不知道那会是什么样子

我建议使用
ObjectEncoder
,它可以将您的
Quote
编码为
ByteBuf


在接收站点上,您需要一个
ObjectDecoder
。之后,您可以在ClientHandler中将收到的消息转换回
Quote

请添加QuoteDecoder和编码器的代码。我添加了它们,但请记住它们从不执行,或者至少它们从不将输出记录到控制台,如果它们的en/de-code方法运行,就会这样做。