Current Location: Home> Function Categories> stream_socket_client

stream_socket_client

Open an Internet or Unix domain socket connection
Name:stream_socket_client
Category:Stream
Programming Language:php
One-line Description:Open a network or Unix domain socket connection

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:

  • $remote_socket: The destination socket address to be connected. For TCP/IP connections, the format is "tcp://hostname:port". For Unix domain sockets, the format is "unix:///path/to/socket".
  • $errno (optional): A reference variable that stores the error number that occurred. If the connection is successful, it will be 0.
  • $errstr (optional): A reference variable that stores the error message that occurs. If the connection is successful, it will be an empty string.
  • $timeout (optional): Connection timeout, in seconds. The default value is "default_socket_timeout" in php.ini.
  • $flags (optional): Connection flag, which can be STREAM_CLIENT_CONNECT (default) or STREAM_CLIENT_ASYNC_CONNECT. When using STREAM_CLIENT_ASYNC_CONNECT, non-blocking mode connections are enabled.
  • $context (optional): A context option for a resource type. Can be used to pass configuration options and parameters.

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.

Similar Functions
Popular Articles