Blade3
Blade3

Reputation: 4360

Reading data from a socket

I am having issues reading data from a socket. Supposedly, there is a server socket that is waiting for clients to connect. When I write a client to connect() to the server socket/port, it appears that I am connected. But when I try to read() data that the server is supposedly writing on the socket, the read() function hangs until the server app is stopped.

Why would a read() call ever hang if the socket is connected? I believe that I am not ever really connected to the socket/port but I can't prove it, b/c the connect() call did not return an error. The read() call is not returning an error either, it is just never returning at all.

Upvotes: 1

Views: 787

Answers (4)

Rakis
Rakis

Reputation: 7864

As John & Whirl mentioned, the problem is almost certainly that the server hasn't sent any data for your read() call to return. Another easy thing to overlook when you're starting out with network programming is that the data transfered in a server's write() call is not always symmetrical with a client's read() call. Where the server may write("hello world"), your read() could easily return "hello world", "hello wo", "hel", or even just "h"

Upvotes: 2

Mark B
Mark B

Reputation: 96233

Unless you explicitly changed your reader's socket to non-blocking mode, a call to read will do exactly what you say until there is data available: It will block forever until some data is actually read.

You can also use netstat (I use it with -f inet) to figure out connections that have been made and see the status of your socket connection.

Upvotes: 1

John Gordon
John Gordon

Reputation: 2704

Your server is probably not writing data to the socket, so your reader just blocks waiting for data to appear on the socket.

Upvotes: 0

WhirlWind
WhirlWind

Reputation: 14112

Read is blocking until is receives some I/O (or an error).

Upvotes: 3

Related Questions