Current Location: Home> Function Categories> socket_connect

socket_connect

Start a connection on a socket
Name:socket_connect
Category:Sockets
Programming Language:php
One-line Description:Connect to the remote host on the created socket

Function name: socket_connect()

Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7

Function Description: The socket_connect() function is used to connect to a remote host on a created socket.

Syntax: bool socket_connect ( resource $socket , string $address [, int $port = 0 ] )

parameter:

  • $socket: The created socket resource is created through the socket_create() function.
  • $address: The IP address or host name of the remote host.
  • $port: (Optional) The port number of the remote host, default is 0.

Return value: Return true on success, and false on failure.

Example:

 // 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "\n"; } // 连接到远程主机$address = "127.0.0.1"; $port = 80; $result = socket_connect($socket, $address, $port); if ($result === false) { echo "socket_connect() failed: " . socket_strerror(socket_last_error($socket)) . "\n"; } // 发送数据到远程主机$data = "Hello, World!"; socket_write($socket, $data, strlen($data)); // 从远程主机接收数据$response = socket_read($socket, 1024); // 关闭套接字socket_close($socket);

The above sample code demonstrates the complete process of creating a socket, connecting to a remote host, sending data to a remote host, receiving data from a remote host, and closing a socket. Please modify the IP address and port number of the remote host according to actual needs.

Similar Functions
Popular Articles