Current Location: Home> Function Categories> socket_send

socket_send

Send data to the connected socket
Name:socket_send
Category:Sockets
Programming Language:php
One-line Description:Send data on connected socket

Function name: socket_send()

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

Usage: int socket_send ( resource $socket , string $buf , int $len , int $flags )

Description: The socket_send() function is used to send data on connected sockets. This function sends the specified data to the other end of the socket connection.

parameter:

  • $socket: Connected socket resource, created through socket_create() and socket_connect().
  • $buf: The data to be sent must be of string type.
  • $len: The length of data to be sent.
  • $flags: Optional parameter, which can be set to one of the following constants:
    • MSG_OOB: Send out-of-band data.
    • MSG_EOR: Add an EOR (end-of-record) tag at the end of the data.
    • MSG_EOF: Send a file ending character.
    • MSG_DONTROUTE: No routing table is used to send data.

Return value: Returns the number of bytes sent when successful, and returns FALSE when failure.

Example:

 // 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "\n"; exit; } // 连接到服务器$result = socket_connect($socket, '127.0.0.1', 8080); if ($result === false) { echo "socket_connect() failed: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } // 发送数据$data = "Hello, server!"; $bytesSent = socket_send($socket, $data, strlen($data), 0); if ($bytesSent === false) { echo "socket_send() failed: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } echo "Sent $bytesSent bytes to server.\n"; // 关闭套接字socket_close($socket);

In the above example, we first create a socket and then connect the socket to the server through the socket_connect() function. Next, we use the socket_send() function to send a string data to the server. Finally, we closed the socket.

Please note that the IP address and port number in the example are only used as examples and you need to modify it to the correct value according to the actual situation.

Similar Functions
Popular Articles