简体   繁体   English

Netty客户端,连接到服务器后停止

[英]Netty client, stops after connection to server

I just started with Netty . 我刚从Netty开始。

Currently I am trying to send an Object to a Server. 目前,我正在尝试将Object发送到服务器。 I wrote some client in Java , and it's working fine. 我用Java编写了一些客户端,并且运行良好。 I also wrote an Android App that receives messages from a server. 我还编写了一个Android应用程序,用于接收来自服务器的消息。 I tried to add some code for handling Object s to the Client part, but there is a problem. 我试图将一些用于处理Object的代码添加到Client部分,但是存在问题。

It connects, but it's not sending messages. 它已连接,但未发送消息。 The Server is the same, so is the Object . 服务器是相同的, Object Manifest is ok. 清单还可以。 I've tried multiple times to lunch Java client and Android client. 我已经尝试过多次午餐Java客户端和Android客户端。 Everything is working for Java . 一切都适用于Java I am desperate already. 我已经绝望了。

Here is my code 这是我的代码

Client 客户

public final class ObjectEchoClient {

    public static ChannelHandlerContext ctx;
    static final String HOST = System.getProperty("host", "192.168.0.101");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));


    public static void startClient() throws Exception {


        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 128)
             .option(ChannelOption.SO_KEEPALIVE, true) // (4)
             .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    p.addLast(
                            new ObjectEncoder(),
                            new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new ObjectEchoClientHandler());
                }
             });

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


        } finally {
            group.shutdownGracefully();
        }
    }
}

Android MainActivity Android MainActivity

public class MainActivity extends Activity {
    public static UnixTime m;
    public static int id = 12345678;
    public static ChannelHandlerContext ctx;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        socketTest();

        final Button btn1 = (Button)findViewById(R.id.button1);


        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    //*
                    if(ObjectEchoClient.ctx != null)
                    { 
                        Package p = new Package();
                        p.setId(id);
                        ObjectEchoClient.ctx.writeAndFlush(p);
                    }
                    else
                    {
                        Log.e("test", "off");
                    }
                    //*/
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }
public static void socketTest()
    {
        new Thread (new Runnable() {

            @Override
            public void run() {
                try {
                    ObjectEchoClient.startClient();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
            }}).start();

    }

PS If I add some message to the handler at the channelActive method in the ObjectEchoClientHandler() , it will be sent. PS:如果我在ObjectEchoClientHandler()channelActive方法中向处理程序添加一些消息,它将被发送。 but I need to send it when I will need to. 但我需要在需要时发送。

PPS Hendler PPS亨德勒

public class ObjectEchoClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        ObjectEchoClient.ctx = ctx;

    }



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

    }

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

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

I am a bit rusty here but when you call: 我在这里有点生锈,但是当你打电话时:

b.connect(HOST, PORT).sync().channel().closeFuture().sync(); b.connect(主机,端口).sync()。channel()。closeFuture()。sync();

are you not closing the channel as soon as it's opened ? 您不立即打开频道就关闭它吗?

Sending a message on channel active is sending during the brief period the channel is connected, no ? 在短时间内正在连接的通道上正在活动的通道上发送消息,否?

I'm still a netty3 diehard but looking at the 5 samples, to connect you want to: 我仍然是一个netty3顽固分子,但请查看5个示例,以连接到您想要:

ChannelFuture f = b.connect(HOST, PORT).sync(); ChannelFuture f = b.connect(HOST,PORT).sync();

And then later, to stop the client: 然后再停止客户端:

f.channel().closeFuture().sync(); 。f.channel()closeFuture()同步();

So the problem was in the writeAndFlush(); 因此问题出在writeAndFlush(); method. 方法。 For Android it's not flushing properly data. 对于Android,它无法正确刷新数据。 So You need to flush it, once again. 因此,您需要再次冲洗它。

ObjectEchoClient.ctx.writeAndFlush(p);
ctx.flush();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM