How to implement a server-side socket in PHP
PHP in how to achieve a server-side socket, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Realize
Related functions: socket_create, socket_set_block, socket_bind, socket_listen, socket_accept, socket_read, socket_write. The specific parameters of these functions are described in detail in the PHP document. I will not repeat them here, but only describe how the server handles the request.
/ / make sure there is no timeout set_time_limit (0) when connecting to the client; / / set IP and port number $address = "127.0.0.1"; $port = 54321 female socketServer = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ("socket_create () socketServer:". Socket_strerror (socket_last_error ()) / n); / / set to blocking mode socket_set_block ($socketServer) or die ("socket_set_block () fail:". Socket_strerror (socket_last_error ()) / / bind port $result = socket_bind ($socketServer, $address, $port) or die ("socket_bind () fail:". Socket_strerror (socket_last_error ()) "/ n"); / / start listening $result = socket_listen ($socketServer, 4) or die ("socket_listen () fail:". Socket_strerror (socket_last_error ()) / n); do {/ / receives the connection request and returns a child Socket to process the information between the client and the server $sock = socket_accept ($socketServer) or die ("socket_accept () failed: reason:". Socket_strerror (socket_last_error ()) "/ n"); while ($sock) {/ / read client data echo "Read client data\ n"; $length = socket_read ($sock, 4); $length = unpack ('length, $length); echo "length:$length [1]\ n"; $request = socket_read ($sock, $length [1]); echo "$request:$request\ n"; / / data transfer returns the result of writing to the client $msg = "this is response message\ n" $msgLength = strlen ($msg); $msgLength = pack ('msgLength, $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)
After receiving the request from the client, it can be processed with the multithreading of PHP, which simply returns the string.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.