Current Location: Home> Function Categories> stream_socket_server

stream_socket_server

Create an Internet or Unix Domain Server Socket
Name:stream_socket_server
Category:Stream
Programming Language:php
One-line Description:Creates a server socket resource and returns a stream resource that listens to the specified local or remote address

Function name: stream_socket_server()

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

Function Description: The stream_socket_server() function creates a server socket resource and returns a stream resource that is used to listen for the specified local or remote address.

Syntax: resource stream_socket_server(string $local_socket, int &$errno = null, string &$errstr = null, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, resource $context = null)

parameter:

  • $local_socket: Required, specify the address to which the server listens. For example, "tcp://127.0.0.1:8000" means port 8000 that listens to the local IP address.
  • &$errno: Optional, references the passed variable, used to store error codes.
  • &$errstr: Optional, references the passed variable to store error information.
  • $flags: Optional, used to specify the behavior option for server sockets, defaults to STREAM_SERVER_BIND | STREAM_SERVER_LISTEN.
  • $context: Optional, to specify the context option for the socket.

Return value: Returns a stream resource of a server socket resource when successful, and returns false when failure.

Example:

 // 创建一个TCP 服务器套接字,并监听本地的8000端口$serverSocket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr); if (!$serverSocket) { die("创建服务器套接字失败:$errstr ($errno)"); } // 接受客户端连接并处理请求while ($clientSocket = stream_socket_accept($serverSocket)) { // 处理客户端请求// ... // 关闭客户端连接fclose($clientSocket); } // 关闭服务器套接字fclose($serverSocket);

In the example above, we use the stream_socket_server() function to create a TCP server socket and specify the 8000 port with the address 127.0.0.1 to listen. We then accept client connections using the stream_socket_accept() function and process client requests in a loop. Finally, close client connection and server sockets through the fclose() function.

Please note that the above example is just a simple example, and more complex processing logic and error handling may be required in practical applications.

Similar Functions
Popular Articles