implementation

Correlation function: Socket_create, socket_set_block, socket_bind, socket_listen, socket_accept, socket_read, and socket_write are specified in the PHP documentation. I won’t go into details here, but I’ll show you how the server handles the request.

Set_time_limit (0); $address = "127.0.0.1"; $port = 54321; $socketServer = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() fail:" . socket_strerror(socket_last_error()) . "/n"); Socket_set_block ($socketServer) or die("socket_set_block() fail:". Socket_strerror (socket_last_error()). "/n"); $result = socket_bind($socketServer, $address, $port) or die("socket_bind() fail:" . socket_strerror(socket_last_error()) . "/n"); $result = socket_listen($socketServer, 4) or die("socket_listen() fail:" . socket_strerror(socket_last_error()) . "/n"); $sock = socket_accept($socketServer) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n"); While ($sock){echo "Read client data \n"; $length = socket_read($sock, 4); $length = unpack('i', $length); echo "length:$length[1] \n"; $request = socket_read($sock, $length[1]); echo "$request:$request \n"; $MSG = "this is response message \n"; $msgLength = strlen($msg); $msgLength = pack('i', $msgLength); socket_write($sock, $msgLength); socket_write($sock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) ."/n"); break; } } while (true); socket_close($socketServer);Copy the code

After receiving the request from the client, it can be processed in combination with PHP’s multithreading, which simply returns a string.

conclusion

Each major language implements socket communication in a similar way, and the process on the server side is almost the same. In cases where there is a high performance socket communication framework, it is recommended not to implement it yourself, but to understand the underlying implementation of the framework.

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, Redis, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc. Many knowledge points can be free to share with you