如何处理Netty中远程服务器的响应?

时间:2015-10-16 01:13:52

标签: java sockets asynchronous netty nio

关于如何在Netty客户端读取字符串响应(我是Netty的新手),我正在努力2天。问题是:

  • 我必须连接到外部服务器,主机是“api.xxx.xx”和端口8443.
  • 服务器请求有自己的消息协议(如代码所示 - json格式的数组[,,,,])。
  • 服务器响应看起来类似(json格式)。

嗯......当我使用普通的Java套接字时,一切正常(相应的代码被注释)。但是,当我尝试使用Netty异步套接字编程时,没有任何反应:(我做错了什么?

public class Client
{
    private static final StringDecoder DECODER = new StringDecoder();
    private static final StringEncoder ENCODER = new StringEncoder();

    public static void main(String[] args) throws Exception
    {
        String data = "[\"get\",\"/products/{id}\",{\"$data\":{\"id\":\"561e33873dd9172f64814a3e\"},\"$client\":\"lucas\",\"$key\":\"04pRgDl9H\"}]\n";
        
        /*SocketFactory factory = SSLSocketFactory.getDefault();

        Socket socket = factory.createSocket("api.schema.io", 8443);

        System.out.println(socket.isConnected());

        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);
        DataInputStream input = new DataInputStream(socket.getInputStream());

        writer.write("[\"get\",\"/products/{id}\",{\"$data\":{\"id\":\"561e33873dd9172f64814a3e\"},\"$client\":\"lucas\",\"$key\":\"04pRgDl9HNZjCxKmweBM3XO5QqcY127nyVvTbtis\"}]\n");

        writer.flush();

        byte b;
        ByteBuffer bb = ByteBuffer.allocate(2048);

        while((b = input.readByte()) != '\n'){
            bb.put(b);
        }

        // Here I got the right response:
        // {"$links":{"variants":{"url":"/products:variants?parent_id={id}"},"bundle_items":{"links":{"*":{"product":{"url":"/products/{product_id}"}}}},"images":{"links":{"*":{"file":{"links":{"data":{"url":"/:files/{id}/data"}}}}}},"category":{"url":"/categories/{category_id}"},"categories":{"url":"/categories:products?product_id={id}"},"stock":{"url":"/products:stock?parent_id={id}"},"reviews":{"url":"/products:reviews?parent_id={id}"}},"$url":"/products/561e33873dd9172f64814a3e","$collection":"com.products","$data":{"name":"iPhone","price":3200,"sale_price":3599,"type":"standard","bundle":false,"virtual":false,"delivery":"shipment","sku":"12","code":"12334","tax_class":"standard","slug":"iphone","variable":true,"stock_tracking":true,"currency":"BRL","date_created":"2015-10-14T10:50:47.044Z","active":false,"id":"561e33873dd9172f64814a3e"},"$time":4,"$status":200}
        System.out.println(new String(bb.array()));

        input.close();
        writer.close();
        socket.close();*/

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast(DECODER);
                pipeline.addLast(ENCODER);

                // Here I need to read the response... But the execution not even get here... :(
                pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

                        System.out.println("RESPONSE HAS ARRIVED!");

                        System.out.println(msg);

                    }
                });

            }
        });

        // Start the client.
        Channel c = b.connect("api.schema.io", 8443).sync().channel();

        c.writeAndFlush(data);

        c.closeFuture().sync();

        workerGroup.shutdownGracefully();

    }
}

抱歉这个菜鸟问题。但我已经尝试了一切。

0 个答案:

没有答案