开发者

Reading data from a socket

开发者 https://www.devze.com 2022-12-28 10:41 出处:网络
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, i

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.


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


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"


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.


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

0

精彩评论

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

关注公众号