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.

php-blocking-socket-1

Example Code Breakdown

References


  1. Network Socket; ↩︎

  2. PHP socket official document ↩︎

  3. Socket Programming ↩︎

  4. Socket Programming in PHP ↩︎

ссс