Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In Linux,

I am programming simple chatting program using client-server structure. It includes file transfer function too.

I designed format used when client transfer file's data to server like this.

(1 byte that display this is file data) (2 byte information to distinguish sender, receiver) (1 byte that informs what current data sending size is) (DATA..............)

above information will be stored on buf[] (char[])

of course, sender use write call to send file data, receiver use read call to receive file data.

I wonder that above format can be fragmented when read, write function using socket descriptor used.

for example, sender write sbuf[] = "abcdefgh". does receiver read rbuf[] = "abcdefgh" always? or rbuf[] could be = "a" or "ab" or "abc" or "abcd" or .... something?

share|improve this question
8  
Assuming tcp, yes the data can fragment between reads. You may have to read and buffer between multiple reads before you get all your data. The return value from the read will tell you how many bytes were read with that call. – Duck Mar 18 at 5:16
3  
Btw: Also a call to write() does not necessarily writes out as many bytes as specfified and needs to be repeated. Always check the value returned by system calls. – alk Mar 18 at 7:23
@Duck Can I get where reference is? I looked read, write from linux system call linux manual. However, it didn't mention about fragmentation and I couldn't find :(. Thanks you for your help in advance. – podray Mar 19 at 11:52
@podray - it has as much (or more) to do with tcp as read. tcp is stream oriented and doesn't honor datagram boundries. It can send 20 bytes in a packet or 2000 depending on its own algorithms. You can't count on how it is going to break the data up. On the read side read is just going to return how many bytes are present (up to the limit you specify) in the tcp buffer. Again, it can be 1 byte or 10000 bytes. Neither tcp nor read has any notion of what your program considers to be a message. It is just a long stream of bytes coming and going. – Duck Mar 20 at 15:39

1 Answer

Yes it can, and probably will. You should consider using recv and send instead of read and write. Using recv you may set the option MSG_WAITALL, that will make the read blocks until the full amount of data can be returned. (for SOCK_STREAM) Please take a look at the man recv/send for more information.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.