views:

211

answers:

2

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.

+2  A: 

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.

Nicolás
http://www.codeproject.com/KB/IP/socketmessageboundary.aspx
Nicolás
also, lameness number 20: http://tangentsoft.net/wskfaq/articles/lame-list.html#item20
Nicolás
+2  A: 

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.
Costique