Netty客户端代码+protobuf

package com.oztf.common.netty;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

import java.util.UUID;

import com.google.protobuf.Any;
import com.oztf.common.protobuf.BaseProto;
import com.oztf.common.protobuf.BrnnProto;
import com.oztf.common.protobuf.UserProto;


public class NettyClient {
    
    private Channel channel;
    
    public Channel connect(String host, int port) {
        doConnect(host, port);
        return this.channel;
    }

    private void doConnect(String host, int port) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 实体类传输数据,protobuf序列化
                    ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast(new ProtobufDecoder(BaseProto.Base.getDefaultInstance()));
                    ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                    ch.pipeline().addLast(new ProtobufEncoder());
                    ch.pipeline().addLast(new ProtoBufServerHandler());
                    
               
                }
            });

            ChannelFuture f = b.connect(host, port).sync();
            f.addListener(new ChannelFutureListener() {  
                public void operationComplete(ChannelFuture future) throws Exception {  
                    if(future.isSuccess()){  
                        System.out.println("client connected111");  
                    }else{  
                        System.out.println("server attemp failed22");  
                        future.cause().printStackTrace();  
                    }  
                      
                }  
            });  
            channel = f.channel();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
发布了5 篇原创文章 · 获赞 0 · 访问量 67

猜你喜欢

转载自blog.csdn.net/swj_soft/article/details/104041542
今日推荐