一次从一个 TCP 套接字向另一个 TCP 套接字发送超过 32768 字节
嘿伙计们,我不知道这个问题是否已经被问过,但想象一下以下情况:
我有两个 TCP 套接字(用 NSSocketPort
打开并用两个 NSFileHandle
监听)现在我想在它们之间发送一些 NSData
。
@try {
[fileHandle writeData:data];
}
@catch (NSException * e) {
// Do some alert
}
一切正常,直到我想发送长度超过 32768 字节的 NSData
实例。超过此字节数将不会被传输。所以我的问题是:
1)为什么 Cocoa 不能一次发送超过 32768 字节?
2)我必须想办法吗?
3)如果是的话,我会拆分数据,但是你会怎么做呢?另一个套接字如何知道所有数据何时发送?
顺便说一句,发送这个单一的 NSData 实例后,两个套接字都应该再次关闭。
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.
@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. 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?
2) Do I have to make workaround?
3) If yes, I would split the data, but how would you do it? 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一次发送的数据量取决于底层框架和库使用的缓冲区的大小。虽然它可能是可配置的,但它基本上是无关紧要的。 TCP 的优点是它要么保证传送数据(在一个或多个数据包中),要么优雅地失败。
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.
您的问题不在于 Cocoa,而似乎是对流套接字的概念误解。
TCP是一种流协议。单独写入的边界将不会被保留。
如果发送 32768 字节,接收端应准备好 readData(或任何名称)返回从单个字节到 32768 字节的任何位置。如果您得到的内容少于 32768 字节,那么您应该再次阅读以获取剩余的内容。或者也许不是所有其他的,你必须再读一遍。由您设计网络协议,以便接收端知道何时获得所有数据;例如,通过在数据前加上其长度作为前缀。
如果 writeData 发送的数据少于您告诉它发送的数据,请使用其余数据再次调用 writeData。并做好准备,发送的数据也会少于您的要求。
Your problem is not with Cocoa but appears to be a conceptual misunderstanding of stream sockets.
TCP is a stream protocol. 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. If you get less than 32768 bytes, then you should read again to get the rest. 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. And be prepared for that to also send less than you asked for.