sana
sana

Reputation: 135

Read from socket return value in c++

I need to enforce the return value of read from a socket to equal to zero without closing connection.

I read the following statement in a page saying:

If an end-of-file condition is received or the connection is closed, 0 is returned.

But I don't know how to make it receive that condition after the string I have sent.

Can anyone help?

Upvotes: 0

Views: 1192

Answers (4)

Perhaps you need some multiplexing syscall like poll(2).

You definitely need to read some good material like Advanced Linux Programming or Advanced Unix Programming.

If you need the TCP/IP transmission to transit application messages, you need to care about packaging and fragmenting explicitly yourself (either by having fixed-size messages, or by having some way to know the logical message size during transmission). Be aware that TCP/IP transmission can be fragmented by the network.

Upvotes: 1

A.H.
A.H.

Reputation: 66293

Both the "end of file condition" and the "connection closed" condition tell the receiver that no more data can be received on this socket. You cannot simulate that by sending some magic data.

Besides of calling close on the socket you can use shutdown(2) on the socket to only close either the reading side or the writing side. This might help in limited cases but not in the general case.

Upvotes: 1

user207421
user207421

Reputation: 311054

If you want the peer's read() or recv() to return zero, you must either close the socket or shut it down for output. In either case you can't sent anything else afterwards. If that constraint doesn't suit you, you will have to revise your requirement, as it doesn't make sense.

Upvotes: 1

Mat
Mat

Reputation: 206909

I'm afraid you can't do that.

If you want read to return zero, you need to close the socket. If you don't want to close the socket, you need to signal "end-of-communication" or "end-of-message" as part of your protocol.

A common way of doing that is prefixing each message with its length. That way the receiving side knows when it's read a complete message and do whatever it wants with it.

Upvotes: 2

Related Questions