Socket Programming for PHP

Source: Internet
Author: User
Tags set socket socket error
from:http://www.phppan.com/2011/02/php-socket/

Socket Programming for PHP

Computer processes can use sockets to communicate with other processes, through the socket, where other processes are located transparently. These processes can be on the same computer or on different computers.

In PHP, the socket is loaded in an extended manner, and if the socket-related function cannot be used, confirm that the extension is open.
The following is a simple implementation of a connection-oriented client and server that illustrates the use of some functions, after which a brief description of how these functions are implemented within PHP.

"Client Implementation"
The code shown below is the implementation code for the client:

Set_time_limit (0); $host = "127.0.0.1"; $port = 2046; $socket = Socket_create (Af_inet, Sock_stream, sol_tcp) or Die ("Could not createsocket\n"); Create a socket $connection = Socket_connect ($socket, $host, $port) or Die ("Could not connet server\n");  Connect Socket_write ($socket, "time") or Die ("Write failed\n");//data transfer sends a message to the server while ($buffer = Socket_read ($socket, 1 024, php_normal_read) {    echo ("Data sent Was:time\nresponse was:".) $buffer. "\ n");} Socket_close ($socket);

The client first creates a socket and connects to the server. Sends a time message to the server, waits for the server to return information, reads the server's information, and outputs it.

"Server Implementation"

Set_time_limit (0); $host = "127.0.0.1"; $port = 2046; $socket = Socket_create (Af_inet, Sock_stream, sol_tcp) or Die ("Could not createsocket\n"); Create a socket $result = Socket_bind ($socket, $host, $port) or Die ("Could not bind tosocket\n"); Bind socket to port $result = Socket_listen ($socket, 3) or Die ("Could not set up socket listener\n"); Start listening Connection $spawn = Socket_accept ($socket) or Die ("Could not accept incoming connection\n"); Processing Communication $input = Socket_read ($spawn, 1024x768) or Die ("Could not read input\n"); The data transfer obtains the client input $input = Trim ($input); Echo ' input: ', $input, "\ n"; if ($input = = ' time ') {    $output = date ("y-m-d h:i:s"). "\ n"; Processes the client input and returns the result}else{    $output = "Input error \ n";//Processing client input and returning the result} echo "Output:", $output, "\ n"; Data transfer writes The returned result to the client Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not write output\n"); Close Socketssocket_close ($spawn); Socket_close ($socket);

The server creates a socket, binds the port, listens to the connection, reads the client's data, returns different values based on the client's input, and finally writes the data to the client. Close the socket.
Only this server cannot accept multiple connections and only one operation is completed
"PHP Internal Source code description"
From the internal source of PHP, PHP provides socket programming is to add a layer outside the Socket,bind,listen function, so that it is more simple and convenient to call. But some business logic programs need to be implemented by programmers themselves.
Below we use the Socket_create source code implementation to explain the internal implementation of PHP.
We have mentioned that the socket for PHP is implemented in an extended manner. In the Ext directory of the source code, we find the sockets directory. This directory contains the PHP implementation for the socket. Direct Search for Php_function (socket_create), the implementation of this function was found in the sockets.c file. The code is as follows:

/* {{{proto resource socket_create (int domain, int type, int protocol) U creates an endpoint for communication in the D Omain specified by domain, of type specified by Type */php_function (socket_create) {long arg1, arg2, arg        3;         Php_socket *php_sock = (php_socket*) emalloc (sizeof (php_socket));                if (Zend_parse_parameters (Zend_num_args () tsrmls_cc, "lll", &arg1, &arg2, &arg3) = = FAILURE) {                Efree (Php_sock);        Return  } if (arg1! = af_unix#if Have_ipv6 && arg1! = af_inet6#endif && arg1 ! = af_inet) {php_error_docref (NULL tsrmls_cc, e_warning, "Invalid socket domain [%LD] specified for Argum                ENT 1, assuming af_inet ", arg1);        Arg1 = af_inet; } if (Arg2 >) {php_error_docref (NULL tsrmls_cc, e_warning, "Invalid socket type [%LD] Specif             IED for argument 2, assuming Sock_stream ", arg2);   Arg2 = Sock_stream;        } Php_sock->bsd_socket = socket (arg1, arg2, ARG3);         Php_sock->type = arg1;                if (Is_invalid_socket (Php_sock)) {sockets_g (last_error) = errno;                Php_error_docref (NULL tsrmls_cc, e_warning, "Unable to create socket [%d]:%s", errno, Php_strerror (errno tsrmls_cc));                Efree (Php_sock);        Return_false;        } php_sock->error = 0;                                                                                                                                           php_sock->blocking = 1; 1257,1-8 61% Zend_register_resource (Return_value, Php_sock, LE_SOC KET);} /* }}} */

From the implementation of the whole function, the program is basically an error and exception handling. PHP itself introduces the php_socket structure, which is created by invoking the socket function implementation.

PS: For the network programming of PHP, we will explain in detail in the Tipi series articles.
"Socket function"
Function Name Description
Socket_accept () accepts a socket connection
Socket_bind () binds the socket to an IP address and port
Socket_clear_error () Clears the socket error or the last error code
Socket_close () Close a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () Open a socket listener on the specified port
Socket_create_pair () produces a pair of undifferentiated sockets into an array
Socket_create () produces a socket equivalent to a data structure that produces a socket
Socket_get_option () Get socket options
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write
Socket_iovec_delete () Delete an assigned Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () releasing a Iovec resource
Socket_iovec_set () Sets the new data value of the Iovec
Socket_last_error () Gets the last error code for the current socket
Socket_listen () listens for all connections by the specified socket
Socket_read () reads the specified length of data
SOCKET_READV () reads data from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket
Socket_recvmsg () receive messages from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends the data to the connected socket
SOCKET_SENDMSG () Send message to socket
Socket_sendto () sends a message to the socket at the specified address
Socket_set_block () set as block mode in socket
Socket_set_nonblock () set to non-block mode in socket
Socket_set_option () Set socket options
Socket_shutdown () This function allows you to close a read, write, or specified socket
Socket_strerror () returns a detailed error for the specified error number
Socket_write () write data to the socket cache
Socket_writev () write data to a scatter/aggregate array

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.