在 previous Stack Overflow question 中,在构建我的 Akka 套接字服务器时,人们非常乐于向我展示我的方法错误,实际上我现在有一个 Akka 套接字客户端可以发送具有以下框架的消息:
消息长度:4字节 消息类型:4字节 消息有效载荷:(长度)字节
这是我用来发送消息的 iOS 代码:
NSInputStream *inputStream;
NSOutputStream *outputStream;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 9999, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// [inputStream open];
[outputStream open];
NSLog(@"NSData raw zombie is %d bytes.", [rawZombie length]);
uint32_t length = (uint32_t)htonl([rawZombie length]);
uint32_t messageType = (uint32_t)htonl(1);
NSLog(@"Protobuf byte size %d", zombieSighting->ByteSize());
[outputStream write:(uint8_t *)&length maxLength:4];
[outputStream write:(uint8_t *)&messageType maxLength:4];
[outputStream write:(uint8_t *)[rawZombie bytes] maxLength:length];
[outputStream close];
'rawZombie' 变量 (NSData *) 来自以下方法:
- (NSData *)getDataForZombie:(kotancode::ZombieSighting *)zombie {
std::string ps = zombie->SerializeAsString();
NSLog(@"raw zombie string:\n[%s]", ps.c_str());
return [NSData dataWithBytes:ps.c_str() length:ps.size()];
}
我看到的症状是我收到了由 iOS 发送的消息,它的长度是正确的,消息类型 (1) 也是正确的,正文也很好。使用 Scala protobufs 的 Akka 服务器反序列化消息并完美地打印出消息上的所有值。问题是,在我收到该消息后,Akka 服务器立即认为它收到了另一条消息(显然,流中有更多数据)。每次运行 iOS 应用程序时,最后的数据都不相同。
例如,这是来自两个连续消息接收的一些跟踪输出:
received message of length 45 and type 1
name:Kevin
lat: 41.007
long: 21.007
desc:This is a zombie
zombie type:FAST
received message of length 7 and type 4
received message of length 45 and type 1
name:Kevin
lat: 41.007
long: 21.007
desc:This is a zombie
zombie type:FAST
received message of length 164 and type 1544487554
因此您可以看到,在 Akka 服务器收到消息的正确数据之后,它还会收到一些随机的任意废话。鉴于我让 Akka 客户端正常工作而没有这种额外的任意废话,我假设我将 protobuf 对象写入 NSStream 的方式有问题......任何人都可以发现我的愚蠢错误,因为我确信那是什么正在这里发生。
最佳答案
该死的 hell 。我不敢相信我没有看到这个。在此处的代码行中:
[outputStream write:(uint8_t *)[rawZombie bytes] maxLength:length]
我使用值“length”表示要传输的最大字节数。不幸的是,该值已经颠倒了它的“字节序”顺序,以准备通过网络传输。我用 [rawZombie length] 替换了“length”,效果非常好。
:(
关于ios - 从 iOS 发送 C++ Protocol Buffer 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676334/