Function name: stream_socket_client()
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Function description: The stream_socket_client() function opens a network or Unix domain socket connection. It provides an easy way to create a connection that communicates with a remote server or local socket.
Syntax: resource stream_socket_client ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, resource $context ]]]]] )
parameter:
Return value: If the connection is successful, a open socket resource is returned. If the connection fails, false is returned.
Example:
// 连接到远程TCP/IP服务器$socket = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30); if ($socket) { // 发送HTTP请求fwrite($socket, "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); // 读取服务器响应while (!feof($socket)) { echo fgets($socket, 4096); } // 关闭连接fclose($socket); } else { echo "连接失败:$errstr ($errno)"; } // 连接到本地Unix域套接字$socket = stream_socket_client("unix:///var/run/socket.sock", $errno, $errstr, 30); if ($socket) { // 发送自定义协议数据fwrite($socket, "Hello, server!"); // 读取服务器响应$response = fread($socket, 4096); // 处理服务器响应echo $response; // 关闭连接fclose($socket); } else { echo "连接失败:$errstr ($errno)"; }
The above example shows how to use the stream_socket_client() function to connect to a remote TCP/IP server and local Unix domain socket and send/receive data. Please modify the target socket address, sent data and processing response logic according to actual conditions.