概述
1、安装说明
点击下载protocol相关程序
2、发送消息
Msg.proto内容如下:
package com.protocol;
message Msg
{
required bytes head = 1;
optional bytes body = 2;
}
message Head
{
required string head01 = 1;
required int32 head02 = 2;
required string head03 = 3;
}
message Body
{
required string body01 = 1;
required int32 body02 = 2;
required string body03 = 3;
}
说明:每一个消息Msg包含消息头head和消息体body,消息头的定义在Head中,消息体的定义在Body中。
//发送消息如下:
Msg.Builder msgBuilder = Msg.newBuilder();
//构建消息头
Head.Builder msgHeadBuilder = Head.newBuilder();
msgHeadBuilder.setHead01("head01");
msgHeadBuilder.setHead02(2);
msgHeadBuilder.setHead03("head03");
Head head=msgHeadBuilder.build();
msgBuilder.setHead(head.toByteString());
//构建消息体
Body.Builder msgBodyBuilder = Body.newBuilder();
msgBodyBuilder.setBody01("body01");
msgBodyBuilder.setBody02(2);
msgBodyBuilder.setBody03("body03");
Body body=msgBodyBuilder.build();
msgBuilder.setBody(body.toByteString());
Msg msg = msgBuilder.build(); //构建整个消息对象
//添加消息至队列并启动发送线程
msgQueue.add(msg)
if (!sendThreadIsAlive) {
new SendThreadRunnable().start();
}
//一般情况下会另开线程来发送消息
private InputStream inputstream = socket.getInputStream();;
private OutputStream outputStream = socket.getOutputStream();;
private boolean sendThreadIsAlive = false;
.//线程存活标志位
private ConcurrentLinkedQueue<Msg> msgQueue = new ConcurrentLinkedQueue<Msg>(); // 消息发送队列
private class SendThread extends Thread {
@Override
public void run() {
sendThreadIsAlive = true;
//线程开启中将其置为true
while (!msgQueue.isEmpty()) {
try {
if (socket != null && !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown()) {
Msg msg = msgQueue.poll();
if (msg != null) {
try {
outputStream.write(msg.toByteArray());
outputStream.flush();
} catch (IOException e) {
}
} else {
}
} else {
msgQueue.clear();
}
} catch (Exception e) {
}
}
sendThreadIsAlive = false;
//队列中没有消息后将其置为false,标识发送线程结束
}
}
3、接收解析
//同样另开线程来接收Msg,核心代码如下:
byte tmpMsg[] = new byte[2048];
int count = inputstream.read(tmpMsg);
if (count < 0) {
break;
}
byte[] message = new byte[count];
System.arraycopy(tmpMsg, 0, message, 0, count);
// 解析整个消息
Msg msg = Msg.parseFrom(message);
// 解析消息头
ByteString head=msg.getHead();
Head msgHead = Head.parseFrom(head);
// head01
String head01 = msgHead.getHead01();
// head02
int head02 = msgHead.getHead02();
//解析消息体
ByteString body = msg.getBody();
Body msgBody = Body.parseFrom(body);
//获得body的内容
// body01
String body01 = msgHead.getBody01();
// body02
int body02 = msgHead.getBody02();
最后
以上就是时尚薯片为你收集整理的Protocol Buffer使用实例的全部内容,希望文章能够帮你解决Protocol Buffer使用实例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复