PHP Blocking Socket with Server-Client Communication Example Code
Outline
PHP Blocking Socket
Socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network[1].
Briefly, a socket is an endpoint in an computer to communicate with an outside network.
PHP offers socket extension, which implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client[2].
There are basic two types of sockets: blocking and nonblocking. Blocking sockets force your application to wait for data to become available, whereas nonblocking sockets do not. [3] I will show you an example of PHP blocking sockets in which a server communicates with a client.
Example Code
server
Some of the following code is borrowed from Socket Programming in PHP
Client
First, run server's snipped code, then client's, you get local server and client running. And you can type a message in client's terminal, then see a received message in the server's terminal, and a response in the client's terminal.
Example Code Breakdown
-
set_time_limit(int $seconds)
: Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in thephp.ini
-
socket_create(int $domain, int $type, int $protocol)
: Initiate a socket. (official doc)AF_INET
: IPv4 Internet based protocols.SOCK_STREAM
: A sequenced and reliable bidirectional connection-based stream. Most common in use.SOL_TCP
: TCP connections
-
socket_bind
: Bind the socket to port and host -
socket_listen
: Server waits for the client to connect -
socket_accept
: Accepts incoming connection request on the created socket. After accepting the connection from client socket, this function returns another socket resource that is actually responsible for communication with the corresponding client socket. Here “$spawn” is that socket resource which is responsible for communication with the client socket.[4] -
socket_read
: Read the message from the Client socketPHP_NORMAL_READ
: Socket reading stops at\n
or\r
, so I add\n
at the end of the server response, otherwise the client can't get response message.
-
socket_write
: Send message to the client socket -
socket_close
: Close the socket -
socket_connect
: Connect client to server -
fopen('php://stdin', 'r')
: where the client reads input from