Myfox开发笔记

1.一个头疼的问题,客户端怎么组织随时发送消息,在ManWeb.connect()中通过Sendmessage.ch = f.channel();拿到channel然后保存到另一个类里面就好了,channel.writeandflush可以写消息。(参见channel官方文档)

public class ManWeb {
    public static int serverport = 18872;
    public static String serverip = "47.106.92.228";

    public static void connect()throws Exception{
        // 配置NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // Bootstrap 类,是启动NIO服务器的辅助启动类
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception{
                            //
                            ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());

                            ch.pipeline().addLast(new ProtobufDecoder(MessageProbuf.Message.getDefaultInstance()));
                            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            ch.pipeline().addLast(new ProtobufEncoder());
                            ch.pipeline().addLast(new Clienthandler());

                        }
                    });

            // 发起异步连接操作
            ChannelFuture f= b.connect(serverport,serverip).sync();

            Sendmessage.ch = f.channel();

            // 等待客服端链路关闭
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }

}
public class Sendmessage{
    public static channel ch;

    //Clienthandler.channalActive use senderid to notify server online
    public static int senderid;
    public static String sendername;

    public static void send(MessageProbuf.Message mess){
        ch.writeAndFlush(mess);
    }
}

 

posted on 2018-06-16 23:42  CreatorKou  阅读(635)  评论(0编辑  收藏  举报

导航