Current Location: Home> Function Categories> socket_recvmsg

socket_recvmsg

Read a message
Name:socket_recvmsg
Category:Sockets
Programming Language:php
One-line Description:Receive message

Function name: socket_recvmsg()

Applicable version: PHP 8.0.0 and above

Usage: socket_recvmsg(resource $socket, SocketMsgFlags &$flags) : SocketMsg

parameter:

  • $socket: represents a valid socket resource for receiving messages.
  • &$flags: A reference parameter, used to receive flag bits when receiving messages.

Return value:

  • Returns a SocketMsg object containing the details of the received message.

Example:

 // 创建一个TCP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() 失败: " . socket_strerror(socket_last_error()) . "\n"; exit; } // 绑定socket 到IP 地址和端口if (socket_bind($socket, '127.0.0.1', 8080) === false) { echo "socket_bind() 失败: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } // 监听连接if (socket_listen($socket, 5) === false) { echo "socket_listen() 失败: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } // 接受客户端连接$clientSocket = socket_accept($socket); if ($clientSocket === false) { echo "socket_accept() 失败: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } // 接收消息$flags = MSG_WAITALL; $message = socket_recvmsg($clientSocket, $flags); if ($message === false) { echo "socket_recvmsg() 失败: " . socket_strerror(socket_last_error($clientSocket)) . "\n"; exit; } // 打印接收到的消息echo "接收到的消息:\n"; var_dump($message); // 关闭socket 连接socket_close($clientSocket); socket_close($socket);

illustrate:

  • In the example, a TCP socket is first created and bound to the local IP address and port.
  • Then listen for the connection request through the socket_listen() function, and accept the client connection through the socket_accept() function, obtaining a new socket resource $clientSocket.
  • Finally, the message sent by the client is received by calling the socket_recvmsg() function and stored in the $message variable.
  • Finally, we print out the received message and close the socket connection.

Please note that this example only demonstrates the basic usage of the socket_recvmsg() function, and may require appropriate modification and error handling according to specific needs when using it.

Similar Functions
Popular Articles