Current Location: Home> Function Categories> socket_sendmsg

socket_sendmsg

Send a message
Name:socket_sendmsg
Category:Sockets
Programming Language:php
One-line Description:Send messages via socket

Function name: socket_sendmsg()

Applicable version: PHP 7.2.0 and above

Function description: socket_sendmsg() function is used to send messages through sockets.

Syntax: bool socket_sendmsg(resource $socket, array $message, int $flags = 0)

parameter:

  • $socket: Socket resource, created by socket_create() function.
  • $message: an array containing messages, including the following key names:
    • 'iov': an array containing message data, each element is a string.
    • 'control': an array containing control information, each element is a string.
    • 'flags': Specify the flag bit of the message.
  • $flags: Optional parameter, used to specify the flag bit for sending the message, default is 0.

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

Example:

 // 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 连接到服务器$connect = socket_connect($socket, '127.0.0.1', 8080); if ($connect === false) { echo "连接失败:" . socket_strerror(socket_last_error($socket)); exit; } // 构建消息数组$message = [ 'iov' => ['Hello, Server!'], 'control' => [], 'flags' => 0, ]; // 发送消息if (socket_sendmsg($socket, $message, 0) === false) { echo "发送消息失败:" . socket_strerror(socket_last_error($socket)); } else { echo "消息发送成功!"; } // 关闭套接字socket_close($socket);

Notes:

  • Before using the socket_sendmsg() function, you need to create a socket and connect to the server.
  • The parameter $message is an associative array, where the value corresponding to the 'iov' key is an array containing message data, which can contain multiple elements, each element is a string representing a message.
  • The corresponding value of the 'control' key in the parameter $message is an array containing control information, and each element is also a string, representing a control information.
  • The parameter $flags can be used to set the flag bit of the message, for example, setting it to MSG_DONTWAIT can set the sending operation to non-blocking mode.
  • When the function returns false, you can use the socket_strerror() function to obtain specific error information.
Similar Functions
Popular Articles