tags:

views:

60

answers:

3

I need to have my PHP application (its a stand alone, not web-based) connect to a server, and also host a tcp socket for things to connect to it.. but since php isnt multi-threaded, i cant have the server listen on one socket, and host another at the same time! it all has to be in one file. is it possible to run both of these side by side?

A: 

Use non blocking sockets. See socket_set_nonblock() and related functions.

konforce
+2  A: 

As an alternative to konforce's answer, use socket_select() to listen to both sockets at once. It will tell you which sockets are able to be read/written when it returns. As pdb and konforce both rightly pointed out, you'll need to put the socket in non-blocking mode with socket_set_nonblock(). Once socket_select() tells you that a socket is ready, write or read as much as possible for each ready socket, then call socket_select() again.

Jack Kelly
I don't see why you need non-blocking sockets for select. Select in C at least guarantees you'll return immediately, even if it's with a short byte count and EAGAIN.
Matt Joiner
From `man 2 select`, heading BUGS: Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use `O_NONBLOCK` on sockets that should not block.
Jack Kelly
+1  A: 

You will need both, socket_select AND non-blocking sockets.

For example socket_select tells you that the socket is writable but doesn't tell you how much bytes you can send without blocking.

pdb