SoFunction
Updated on 2025-03-09

PHP implements client and server communication functions based on socket

This article mainly introduces the simple client and server communication function implemented by PHP based on socket, which can realize the function of receiving strings sent by the client and returning to the client after flipping. Friends who need it can refer to it.

Server:

<?php
 set_time_limit(0);
 $host="localhost";
 $port=1001;
 //Create a connection $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
 //Bind socket to port $result=socket_bind($socket,$host,$port) or die("cannot bind port to socket\n");
 //Start listen to this port $result=socket_listen($socket,4) or die("could not set up socket listen\n");
 // Accept connection, another socket to handle communication $msgsock=socket_accept($socket) or die("cannot accept incoming connection\n");
 if($msgsock){
  echo date("Y-m-d H:i:s D a");
 }
 //Read the information sent by the client $input=socket_read($msgsock,1024) or die("cannot read input\n");
 $input=trim($input);
 $output=strrev($input)."The order is reversed\n";
 // Process the received information and return to the client socket_write($msgsock,$output,strlen($output)) or die("cannot write");
 //Close the socket connection socket_close($msgsock);
 socket_close($socket);
?>

Client:

<?php
 set_time_limit(0);
 $host="localhost";
 $port=1001;
 //Create a socket $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
 $conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");
 if($conn){echo "client connect ok!";}
 socket_write($socket,"hello world!") or die("cannot write data\n");
 $buffer=socket_read($socket,1024,PHP_NORMAL_READ);
 if($buffer){
  echo "response was:".$buffer."\n";
 }
 socket_close($socket);
?>


The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.