Current Location: Home> Function Categories> stream_socket_sendto

stream_socket_sendto

Send a message to the socket, whether it is connected or not
Name:stream_socket_sendto
Category:Stream
Programming Language:php
One-line Description:Send data to the specified socket

Function name: stream_socket_sendto()

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

Function description: stream_socket_sendto() function is used to send data to the specified socket.

usage:

 int stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string &$error_message ]] )

parameter:

  • $socket: Required, a valid socket resource created by stream_socket_client(), stream_socket_server(), or stream_socket_accept() functions.
  • $data: Required, data to be sent.
  • $flags: Optional, used to specify the option to send data, default is 0.
  • $error_message: Optional, if sending fails, the string that will store the error message.

Return value:

  • Returns the number of data bytes sent when successful, and returns false when failure.

Example:

 // 创建套接字$socket = stream_socket_client('tcp://www.example.com:80', $errno, $errstr, 30); if (!$socket) { echo "Failed to connect: $errstr ($errno)"; } else { $data = "Hello, server!"; $bytesSent = stream_socket_sendto($socket, $data); if ($bytesSent === false) { echo "Failed to send data."; } else { echo "Sent $bytesSent bytes of data."; } fclose($socket); }

In the above example, we first create a socket using the stream_socket_client() function, and then use the stream_socket_sendto() function to send data to the socket. If the sending is successful, the number of data bytes sent will be output; if the sending fails, an error message will be output. Finally, we use the fclose() function to close the socket. Please note that the "tcp: //www.example.com:80 " in the example is just an example, and you need to replace it with a valid socket address according to the actual situation.

Similar Functions
Popular Articles