Listing 1: A Simple TCP-Server Written In PHP

 1 #!/usr/local/bin/php -q
 2 
 3 <?php
 4 	/*
 5 	 * We don't want any time-limit for how the long can hang
 6 	 * around, waiting for connections:
 7 	*/
 8 	set_time_limit(0);
 9 
10 	/* Create a new socket: */
11 	if( ($sock = socket( AF_INET, SOCK_STREAM, 0 )) < 0 )
12 	{
13 		print strerror( $sock ) . "\n";
14 		exit(1);
15 	}
16 
17 	/* Bind the socket to an address and a port: */
18 	if( ($ret = bind( $sock, "127.0.0.1", 10000 )) < 0 )
19 	{
20 		print strerror( $ret ) . "\n";
21 		exit(1);
22 	}
23 
24 	/*
25 	 * Listen for incoming connections on $sock.
26 	 * The '5' means that we allow 5 queued connections.
27 	*/
28 	if( ($ret = listen( $sock, 5 )) < 0 )
29 	{
30 		print strerror( $ret ) . "\n";
31 	}
32 
33 	/* Accept incoming connections: */
34 	if( ($msgsock = accept_connect( $sock )) < 0)
35 	{
36 		print strerror( $msgsock ) . "\n";
37 		exit(1);	
38 	}
39 
40 	/* Send the welcome-message: */
41 	$message = "Welcome to my TCP-server!\n";
42 	if( ($ret = write( $msgsock, $message, strlen($message)) ) < 0 )
43 	{
44 		print strerror( $msgsock ) . "\n";
45 		exit(1);
46 	}
47 
48 	/* Read/Receive some data from the client: */ 
49 	$buf = '';
50 	if( ($ret = read( $msgsock, $buf, 128 )) < 0 )
51 	{
52 		print strerror( $ret ) . "\n";
53 		exit(1);
54 	}
55 
56 	/* Echo the received data back to the client: */
57 	if( ($ret = write( $msgsock, "You said: $buf\0\n", strlen("You said: $buf\0\n")) ) < 0 )
58 	{
59 		print strerror( $ret ) . "\n";
60 		exit(1);
61 	}
62 	
63 	/* Close the communication-socket: */			
64 	close( $msgsock );
65 
66 	/* Close the global socket: */
67 	close( $sock );
68 ?>