PHP and Socket programming

Source: Internet
Author: User
Tags connect socket get ip set socket socket error

Preface PHP socket connection function has three kinds of schemes
    • 1. Socket integrated in the kernel
      • Fsockopen
      • Pfsockopen
    • 2, PHP extension module with the socket function, compile PHP must be in the configuration --enable-sockets to add configuration items to enable
      • Socket_create
      • Socket_bind
      • Socket_connect
      • Socket_accept
    • 3, based on the function of streams fluidization concept
      • Stream_socket_server
      • Stream_socket_client
      • Stream_socket_accept

This document discusses the second scenario

Socket Basics

PHP uses the Berkley socket library to create its connection. A socket is simply a data structure. Use the socket data structure to open a session between a client and a server. The server has been listening ready to produce a new session. When a client connects to a server, it opens a session on a port that the server is listening on. At this point, the server accepts the client's connection request, then it loops. Now the client is able to send messages to the server, and the server can send messages to the client.
Generating a socket requires three variables: a protocol, a socket type, and a common protocol type.

    • One: agreement
Name/constant Description
Af_inet This is most of the protocol used to generate the socket, using TCP or UDP to transmit, using the address of the IPV4
Af_inet6 Similar to the above, but to use the address of the IPV6
Af_unix Local protocols, used on UNIX and Linux systems, are rarely used, and are typically used when the client and server are on the same platform and on
    • Two: Socket type
Name/constant Description
Sock_stream This protocol is a sequential, reliable, data-complete byte-stream-based connection. This is the most used socket type, which is transmitted using TCP.
Sock_dgram This protocol is a non-connected, fixed-length transfer call. The protocol is unreliable and uses UDP to connect to it.
Sock_seqpacket This protocol is a two-line, reliable connection that sends a fixed-length packet for transmission. This package must be fully accepted to be read.
Sock_raw This socket type provides a single network access, and this socket type uses the ICMP public protocol. (Ping, traceroute Use this Protocol)
Sock_rdm This type is rarely used and is not implemented on most operating systems, it is provided to the data link layer for use, and does not guarantee the order of packets
    • III: Public Agreement
Name/constant Description
Icmp Internet Control Message Protocol, primarily used on gateways and hosts, to check network conditions and report error messages
Udp User data message protocol, which is a non-connected, unreliable transport protocol
Tcp Transmission Control Protocol, which is a reliable public protocol with the most use, ensures that packets can reach the recipient, and if an error occurs during transmission, it will resend the error packet.
Using the PHP socket extension
    • Server-side code:

When you write a server, you must first perform an "accept" operation on the server socket using the Stream_socket_accept feature. This function blocks until the client connects to the server, or the timeout expires.

//Ensure that the client is connected without timing outSet_time_limit(0);//Set IP and port number$address="127.0.0.1";$port=2046;/*** Create a socket* af_inet= is IPv4 if IPv6 is used, the parameter is Af_inet6* Sock_stream is the TCP type of the socket, and if it is UDP use Sock_dgram */$sock=socket_create(af_inet, Sock_stream, sol_tcp) orDie_error();//Blocking modeSocket_set_block($sock) orDie_error();//bind to socket port$result=Socket_bind($sock, $address, $port) orDie_error();//Start monitoring$result=Socket_listen($sock, 4) orDie_error();Echo "OK\ nBinding the socket on$address:$port ... ";Echo "OK\ nNow the ready to accept connections.\ nListening on the socket ...\ n"; Do{//Never stop the daemon    //It receives the connection request and invokes a sub-connection socket to handle the information between the client and the server    $msgsock=socket_accept($sock) orDie_error();    //Read client data    Echo the Read client data\ n";    the//socket_read function reads the client data until it encounters the \n,\t or the/s character. The PHP script considers this character to be the input terminator.    $buf=Socket_read($msgsock, 8192);    Echo "Received msg:$buf  \ n";    //Data transfer writes the returned results to the client    $msg="Welcome\ n";    Socket_write($msgsock, $msg, strlen($msg)) orDie_error();    //Once the output is returned to the client, the parent/child socket should be terminated by the Socket_close ($msgsock) function    Socket_close($msgsock);} while (true);Socket_close($sock);/*** Display Errors * @returnstring */functionDie_error(){$errorcode=Socket_last_error();    $errormsg=Socket_strerror($errorcode);     die("couldn ' t create socket: [$errorcode] $errormsg".Php_eol);}
    • Client code:
Set_time_limit(0);$host="127.0.0.1";$port=2046;//Create a socket$socket=socket_create(af_inet, Sock_stream, sol_tcp) orDie_error();//Connect socket$connection=Socket_connect($socket, $host, $port) orDie_error();//data transfer sends a message to the serverSocket_write($socket, "Hello socket") orDie_error(); while ($buff=Socket_read($socket, 1024x768, Php_normal_read)){Echo ("Response was:".$buff."\ n");}Socket_close($socket);/*** Display Errors * @returnstring */functionDie_error(){$errorcode=Socket_last_error();    $errormsg=Socket_strerror($errorcode);     die("couldn ' t create socket: [$errorcode] $errormsg".Php_eol);}

Php_binary_read-Use the system recv () function. Used to read the security of binary data. (in php> "default = 4.1.0)
Php_normal_read-read stop in? n or \ r (default in PHP <= 4.0.6)
For the parameter php_normal_read, if the server response result is not? n. Cause socket_read (): Unable to read from socket

Socket function
Name of function Description
Socket_accept () Accept a socket connection
Socket_bind () Bind 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 indistinguishable sockets into an array
Socket_create () Generate a socket that is equivalent to generating a data structure for a socket
Socket_get_option () Get socket options
Socket_getpeername () Get IP address of a remote similar host
Socket_getsockname () Get 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 already assigned Iovec
Socket_iovec_fetch () Returns the data for the specified Iovec resource
Socket_iovec_free () Releasing a Iovec resource
Socket_iovec_set () Set the new data value for 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 data of a specified length
SOCKET_READV () Read 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 () To 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 () Send 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
Socket based on streams stream
    • Service side:
# server.php$addr=' 127.0.0.1 ';$port= the;/*** Specify protocol, bind port, add reference two error message prompt parameter* This step completes the Sokect binding */$server=Stream_socket_server("tcp://$addr:$port", $errno, $errorMessage);if ($server===false){Throw New unexpectedvalueexception("Could not bind to socket:$errorMessage");} for (;;){//It receives the connection request and invokes a sub-connection socket to handle the information between the client and the server    $client=@stream_socket_accept($server);    if ($client){//Copy bytes from the stream of the first parameter, as a second parameter stream, and return the client request content        Stream_copy_to_stream($client, $client);        //Close Client connection        fclose($client);}}
    • Client:
# client.php//IP address of the connected host//$addr = gethostbyname ("www.example.com");$addr=' 127.0.0.1 ';$port= the;//Create socket Connection$client=stream_socket_client("tcp://$addr:$port", $errno, $errorMessage);if ($client===false){Throw New unexpectedvalueexception("Failed to connect:$errorMessage");}//Socket connection by Stream_socket_client is a stream, just like opening a file via fopenfwrite($client, "get/http/1.0\ r \ nHost:www.example.com\ r \ nAccept: */*\r\n\r\n");//Get responseEcho stream_get_contents($client);fclose($client);

PHP and Socket programming

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.