开发者

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.

@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 ma开发者_开发问答ke 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.


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.

  1. You don't have to split your data before sending. The underlying system will do that for you.
  2. On the receiving end you can read the available data, then wait until more bytes arrive, process them, and so on, until no more data is available. When the sender completes sending its data, it will close the socket and the receiver will get notified.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜