GCDAsyncSocket在传输数据时会更改数据

编程入门 行业动态 更新时间:2024-10-23 13:22:29
本文介绍了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.

如何使用 GCDAsynsSocket :

NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n"; NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding]; [newSocket writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG]; [newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];

您不必对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在传输数据时会更改数据

本文发布于:2023-10-16 00:28:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   时会   GCDAsyncSocket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!