设为首页 收藏本站
查看: 831|回复: 0

[经验分享] protobuf在Python和Java之间通信测试

[复制链接]

尚未签到

发表于 2015-12-15 08:34:18 | 显示全部楼层 |阅读模式
一 准备protobuf环境
1 下载protobuf-2.6.1,解压,进入vsprojects目录,用VC打开工程,编译出 protoc.exe
2 生成.proto文件
message TestMsg
{
   required string name = 1;
}
放到自己的目录,此例子中放到了f:根目录下。
然后执行:
protoc.exe -I=f:\ --python_out=f:\ f:\TestMsgProto.proto
生成 TestMsgProto_pb2.py,给python用
protoc.exe -I=f:\ --java_out=f:\ f:\TestMsgProto.proto
生成TestMsgProto.java,给java工程用

3 生成对应c++,python,java的class文件

二 python
1 copy protoc.exe到protobuf-2.6.1/python
2 python setup.py build
3 python setup.py install
4 测试用客户端代码:

import google.protobuf
import TestMsgProto_pb2
import socket
address = ('127.0.0.1', 8800)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
msg = TestMsgProto_pb2.TestMsg()
msg.name='name'
test_str = msg.SerializeToString()
print test_str
ret=s.send(test_str)
print ret
s.close()


三 java环境
可参考:https://github.com/vincepeng/gameNettyDemo
主要看 https://github.com/vincepeng/gameNettyDemo/tree/master/GameNettyServer/bin/com/server/java/netty
这下面的几个文件,可以直接放到自己工程里,或者自己稍改动一下。

注意事项:
新建myeclipse maven工程,pom.xml增加:
<dependency>
   <groupId>io.netty</groupId>
   <artifactId>netty-all</artifactId>
   <version>4.0.30.Final</version>
   <scope>compile</scope>
    </dependency>
<dependency>
   <groupId>com.google.protobuf</groupId>
   <artifactId>protobuf-java</artifactId>
   <version>2.6.1</version>
</dependency>


然后,主要处理:decoder和encoder,相比gameNettyDemo做了些减化,下面是做过修改的代码:
//NettyMsgEncoder
public class NettyMsgEncoder extends MessageToByteEncoder<String> {
@Override
protected void encode(ChannelHandlerContext ctx, String name, ByteBuf byteBuf) throws Exception {

TestMsgProto.TestMsg.Builder builder = TestMsgProto.TestMsg.newBuilder();
builder.setName(name);

TestMsgProto.TestMsg msg = builder.build();
byteBuf.writeBytes(msg.toByteArray());
}
}


// NettyMsgDecoder
public class NettyMsgDecoder extends LengthFieldBasedFrameDecoder {
//以下两个构造函数,在本例中用不上
public NettyMsgDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
}

public NettyMsgDecoder() {
this(ByteOrder.BIG_ENDIAN, 100000, 0, 4, 2, 4, true);
}

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
if (byteBuf != null && byteBuf.readableBytes()>0){
int len = byteBuf.readableBytes();
byte[] data = new byte[len];
byteBuf.readBytes(data);
TestMsgProto.TestMsg msg = TestMsgProto.TestMsg.parseFrom(data);


//return msg.getName();
return msg;
}
return null;
}


}


//NettyServerInitializer
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {


@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decoder", new NettyMsgDecoder())// 解码器
.addLast("encoder", new NettyMsgEncoder())// 编码器
.addLast("handler", new ServerHanlder());
}
}
//ServerHanlder
@Sharable
public class ServerHanlder extends SimpleChannelInboundHandler<TestMsgProto.TestMsg> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TestMsgProto.TestMsg msg)
throws Exception {
if (msg != null)
System.out.println(msg.getName());

}
}

//SimpleChatServer
public class SimpleChatServer {
private int port;


    public SimpleChatServer(int port) {
        this.port = port;
    }


    public void run() throws Exception {


        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             //.childHandler(new SimpleChatServerInitializer())
             .childHandler(new NettyServerInitializer())
             .option(ChannelOption.SO_BACKLOG, 128)         
             .childOption(ChannelOption.SO_KEEPALIVE, true);


            ChannelFuture f = b.bind(port).sync(); // (7)
            f.channel().closeFuture().sync();


        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();


            System.out.println("SimpleChatServer 关闭了");
        }
    }
}


然后,在Myeclipse里运行java服务器程序
再启动python 远程连接,看接收情况。
从代码上看,小项目用python是多么方便。

上面例子只有java netty的server和python的client .
稍做修改,就能实现python的server和java的client,复杂的依然复杂,简洁的依然简洁。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-151284-1-1.html 上篇帖子: Python 内置函数大全 下篇帖子: [Python-Twisted] Twisted入门之端口转发服务器 .
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表