MPMessagePack
MessagePack 框架。
MessagePack 是一种高效的二进制序列化格式。它可以像 JSON 一样在多种语言之间交换数据。但它更快,更小。
Podfile
pod "MPMessagePack"
Cartfile
github "gabriel/MPMessagePack"
MPMessagePack
写入
#import <MPMessagePack/MPMessagePack.h>
NSDictionary *dict =
@{
@"n": @(32134123),
@"bool": @(YES),
@"array": @[@(1.1f), @(2.1)],
@"body": [NSData data],
};
NSData *data = [dict mp_messagePack];
也可以通过 MPMessagePackWriter
实现。
NSError *error = nil;
NSData *data = [MPMessagePackWriter writeObject:dict error:&error];
如果您需要使用有序字典。
MPOrderedDictionary *dict = [[MPOrderedDictionary alloc] init];
[dict addEntriesFromDictionary:@{@"c": @(1), @"b": @(2), @"a": @(3)}];
[dict sortKeysUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSData *data = [dict mp_messagePack];
阅读
id obj = [MPMessagePackReader readData:data error:&error];
MPMessagePackReader *reader = [[MPMessagePackReader alloc] initWithData:data];
id obj1 = [reader read:&error]; // Read an object
id obj2 = [reader read:&error]; // Read another object
RPC
查看 msgpack-rpc。
它还支持一个封装选项,它将在rpc消息前加上字节数(作为msgpack编解码的数字)的前缀。
客户端
带有完成块的请求
MPMessagePackClient *client = [[MPMessagePackClient alloc] init];
[client openWithHost:@"localhost" port:93434 completion:^(NSError *error) {
// If error we failed
[client sendRequestWithMethod:@"test" params:@[@{@"arg": @(1)}] completion:^(NSError *error, id result) {
// If error we failed
// Otherwise the result
}];
}];
您也可以同步请求
NSError *error = nil;
id result = [client sendRequestWithMethod:@"test" params:@[@{@"arg": @(1)}] messageId:3 timeout:5.0 error:&error];
// error.code == MPRPCErrorRequestTimeout on timeout
并取消正在进行的请求
BOOL cancelled = [client cancelRequestWithMessageId:3];
// cancelled == YES, if the request was in progress and we cancelled it
服务器
MPMessagePackServer *server = [[MPMessagePackServer alloc] initWithOptions:MPMessagePackOptionsFramed];
server.requestHandler = ^(NSString *method, id params, MPRequestCompletion completion) {
if ([method isEqualToString:@"echo"]) {
completion(nil, params);
} else {
completion(@{@"error": {@"description": @"Method not found"}}, nil);
}
};
NSError *error = nil;
if (![server openWithPort:93434 error:&error]) {
// Failed to open
}
Mantle 编码
如果您使用 Mantle 将对象编码到 JSON 中(然后是 msgpack),您可以指定 MPMessagePackClient 的编码器
@interface KBMantleCoder : NSObject <MPMessagePackCoder>
@end
@implementation KBMantleCoder
- (NSDictionary *)encodeModel:(id)obj {
return [obj conformsToProtocol:@protocol(MTLJSONSerializing)] ? [MTLJSONAdapter JSONDictionaryFromModel:obj] : obj;
}
@end
然后在客户端
MPMessagePackClient *client = [[MPMessagePackClient alloc] init];
client.coder = [[KBMantleCoder alloc] init];
XPC
这是一个实验性的,但功能性的msgpack-rpc功能,它是基于XPC的(请参阅XPC目录)。更多细节即将揭晓。