TechniqueUse PHP's lower-level socket functions along with the set_time_limit() function to create a simple server: <?php set_time_limit(0); $addr = "127.0.0.1"; $port = 5000; $sock = socket(AF_INET, SOCK_STREAM, 0); if ($sock < 0) die(strerror($sock)); if (($ret = setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, 1)) < 0) print strerror($ret); if (($ret = bind($sock, $addr, $port)) < 0) die(strerror($ret)); if (($ret = listen($sock, 10)) < 0) die(strerror($ret)); while (($csock = accept_connect($sock)) >= 0) { // .. manipulate $csock here. } close($sock); ?> CommentsTo create a TCP server, you must first create a new socket with a domain of AF_INET and a type of SOCK_STREAM (most similar to a UNIX pipe). Then you bind() that socket to an address and port. Following that, you have to tell PHP to listen() on that socket, with a maximum number of connections specified by the second argument. (For portable applications, the number of connections should be a maximum of five because BSD and BSD-derived systems support no more than that.) Finally, you have to accept new connections to the socket. For that, you can use PHP's accept_connect() function, which will accept a new socket that can be both read from and listened to. When you close this socket, a new socket will be accepted. If you just want to open a socket with a given port (with an IP address of 0.0.0.0 ), you can use the open_listen_sock() function: <?php $sock = open_listen_sock(230); while (($msock = accept_connect($sock)) >= 0) { // .. Manipulate $msock } close($sock); ?> |