GCDAsyncSocket在传输数据时会更改数据 [英] GCDAsyncSocket alters data while transporting it

查看:271
本文介绍了GCDAsyncSocket在传输数据时会更改数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个多人iOS游戏,遇到了以下问题:我发送了一个字典,里面有一系列自定义对象.这些自定义对象符合NSCoding.我像这样将字典转换为NSData:

I'm making a multiplayer iOS game and have run into the following issue: i send a dictionary with an array of custom objects inside it. These custom objects conform to NSCoding. I convert the dictionary to NSData like this:

 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:packet];

然后发送

[asyncSocket writeData:data withTimeout:-1 tag:tag];

接收

[sock readDataWithTimeout:-1 tag:tag];

并尝试取消存档

NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];

一切看起来都非常简单,但是取消存档数据时应用程序崩溃了,我收到了以下错误消息

Everything looks extremely simple, but the app crashes while unarchiving the data and i receive the following error

[NSKeyedUnarchiver initForReadingWithData:]:难以理解的存档(0x62、0x70、0x6c,0x69、0x73、0x74、0x30、0x30)'

[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30)'

我查看了对发送和接收的数据的描述,发现数据1)被更改,2)被截断,到达接收器设备.

I looked at the description of the data sent and received and found that the data comes to the receiver device 1)altered and 2)truncated.

当我通过GameKit协议,Game Center和蓝牙发送完全相同的数据时,就不会出现这样的问题-我接收到的数据不变,因此显然问题出在GCDAsyncSocket的深处.

When i send exactly the same data over GameKit protocols, Game Center and bluetooth there's no problem like this - i receive the data unchanged, so obviously problem lies inside somewhere deep in GCDAsyncSocket.

有人遇到过这样的麻烦吗?谢谢

Did anyone ever encounter such a trouble? Thanks

推荐答案

原因如下: TCP协议基于无限长的单个连续流的概念.您需要在data后面附加某种类型的终结符指示符,并使用readDataToData方法.或者,您需要在data前面加上data长度的指示符.因此,当您使用readDataWithTimeout时,可以从传入的TCP流中提取确切的字节数.

It is because of this: The TCP protocol is modeled on the concept of a single continuous stream of unlimited length. You need to either appending to your data some type of terminator indicator and using the readDataToData method. Or you need to prefix your data with an indicator for the length of your data. So when you use readDataWithTimeout, you can extract the exact number of bytes out of the incoming TCP stream.

如何使用

您不必对GameKit进行上述所有操作的原因是因为GameKit协议会为您处理所有这些事情.

The reason why you do not have to do all the mentioned above with GameKit because GameKit protocols take care all of that for you.

这篇关于GCDAsyncSocket在传输数据时会更改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆