[英]Send more than 32768 Bytes at once from one TCP-Socket to an other
Hey guys, I don't know if this question has been asked yet but imagine following situation: 大家好,我不知道是否已经问过这个问题,但请想象以下情况:
I have two TCP-Sockets (opened with NSSocketPort
und listening with two NSFileHandle
) and now I want to send some NSData
between them. 我有两个TCP套接字(使用
NSSocketPort
打开,并使用两个NSFileHandle
监听),现在我想在它们之间发送一些NSData
。
@try {
[fileHandle writeData:data];
}
@catch (NSException * e) {
// Do some alert
}
Everything is right until I want to send a NSData
instance with more than a length of 32768 Bytes. 一切正常,直到我要发送长度超过32768字节的
NSData
实例为止。 More than this number of bytes will not be transfered. 超过此字节数的字节将不会被传输。 So here are my questions:
所以这是我的问题:
1) Why isn't Cocoa able to send more than 32768 Bytes at once? 1)为什么可可不能一次发送超过32768字节?
2) Do I have to make workaround? 2)我必须采取解决方法吗?
3) If yes, I would split the data, but how would you do it? 3)如果是,我将拆分数据,但是您将如何处理? And how would the other socket know when all data is sent?
另一个套接字如何知道何时发送所有数据?
By the way, after sending this single NSData
instance both sockets should be closed again. 顺便说一句,在发送此单个
NSData
实例后,应再次关闭两个套接字。
Your problem is not with Cocoa but appears to be a conceptual misunderstanding of stream sockets. 您的问题不在于Cocoa,而似乎是对流套接字的概念性误解。
TCP is a stream protocol. TCP是流协议。 The boundaries of separate writes will not be kept.
单独写入的边界将不会保留。
If you send 32768 bytes, the receiving end should be prepared for readData (or whatever it's called) to return anywhere from a single byte to 32768 bytes. 如果发送32768字节,则接收端应做好准备,使readData(或任何它所谓的)返回从单个字节到32768字节的任何位置。 If you get less than 32768 bytes, then you should read again to get the rest.
如果少于32768字节,则应再次阅读以获取其余部分。 Or maybe not all the rest, and you have to read yet again.
也许不是所有其他内容,您都必须再次阅读。 It's up to you to design your network protocol so the receiving end knows when it got all the data;
由您决定网络协议,以便接收端知道何时获取所有数据。 for example by prefixing the data with its length.
例如,通过为数据加上长度作为前缀。
If writeData sends less than the data you told it to send, call writeData again with the rest of the data. 如果writeData发送的数据少于您要求发送的数据,请再次使用其余数据调用writeData。 And be prepared for that to also send less than you asked for.
并为此做好准备,以使发送的邮件数量少于您的要求。
The amount of data sent at a time depends on the size of the buffer which the underlying frameworks and libraries use. 一次发送的数据量取决于基础框架和库使用的缓冲区大小。 While it may be configurable, it's mostly irrelevant.
尽管它是可配置的,但基本上无关紧要。 The advantage of TCP is that it either guarantees to deliver your data (in one or more packets) or fails gracefully.
TCP的优点是它可以保证以一个或多个数据包的形式传递数据,也可以正常地失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.