iOS和服务器的protobuf实现

时间:2015-07-29 20:52:42

标签: ios protocol-buffers

我计划在iOS和服务器端使用protobuf来处理数据模型。我选择google protobuf编译器在服务器端生成java模型,并使用objective-c protobuf插件编译器在iOS端生成目标模型。

我有以下问题,希望有人可以提供帮助。

  1. 如何处理网络层?用于向客户端发送数据的内容类型是什么?我找到了一些专家建议" application / octet-stream"有些人建议使用application / x-protobuf。
  2. 如何在客户端使用AFNetworking lib。
  3. 是否有用于iOS服务器protobuf实现的示例项目?

2 个答案:

答案 0 :(得分:0)

尝试使用以协议缓冲区构建的以下RPC框架:http://www.grpc.io/

答案 1 :(得分:0)

我遇到了同样的问题。如何使用AFNetworking发布我的protobuf数据? 我写这些代码:

NSMutableData *protubufData = [[NSMutableData alloc] init];
// 0XFF
int str = 0xff;
str = htonl(str);
[protubufData appendBytes:&str length:sizeof(str)];
// playerId
long playerId = 86966;
playerId = htonll(playerId);
NSData *playerIdData = [NSData dataWithBytes: &playerId length: sizeof(playerId)];
[protubufData appendData:playerIdData];
// sessionId
long sessionId = 1789586966;
sessionId = htonll(sessionId);
NSData *sessionIdData = [NSData dataWithBytes: &sessionId length: sizeof(sessionId)];
[protubufData appendData:sessionIdData];

int commandId = 17895;
commandId = htonl(commandId);
// size
u_long size = params.length+4;
size = htonl(size);
[protubufData appendBytes:&size length:4];
// commandId
NSData *commandIdData = [NSData dataWithBytes: &commandId length: sizeof(commandId)];
[protubufData appendData:commandIdData];
// data
[protubufData appendData:params];

我使用AFN方法:

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                parameters:(id)parameters
                  progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                   success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                   failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure

但收到的protobuf数据不是预期的!

然后我使用NSURLConnection。被遗弃的AFN!

//Step One
NSURL *url = [NSURL URLWithString:baseProUrl];
//Step Two
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:protubufData];
//Step Three
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

//Step Four
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSLog(@"%@",[res allHeaderFields]);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSData *prodata = [data subdataWithRange:NSMakeRange(12, data.length)];
VickyTest_Req *req = [VickyTest_Req parseFromData:prodata error:nil];
NSLog(@"req:%@",req);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%@",[error localizedDescription]);
}

终于成功了!