Simple example of PHP implementation socket

Source: Internet
Author: User

First, Socket introduction

1, socket is just a data structure

2. Use this socket data structure to start a session between the client and server

3, the server is always listening ready to produce a new session. When a client connects to the server, it opens a session on a port on which the servers are listening

4, the server side accepts the client's link request, then carries on the cycle. Now the client is able to send messages to the server, and the server can send messages to the client. Focus

However, the game server is still not PHP, but with Lua or C + +, because PHP has bottlenecks, and quickly reach the bottleneck.

Second, the socket variable

To generate a socket, you need three variables: one is protocol, one socket type and one public protocol type.

1. Agreement

af_inet//the protocol that generated the socket, using TCP or UDP to transmit, using the IPV4 address

af_inet6//the protocol that generated the socket, using TCP or UDP to transmit, used in the IPV6 address

af_unix//local protocols, which are used on UNIX and Linux systems, are rarely used, and are typically used when the client and server are on the same machine

2. Socket type

sock_stream//This protocol is a sequential, reliable, data-complete, byte-stream-based link. 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 link to it.

sock_seqpacket//This protocol is a two-line, reliable link 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, this socket type uses the ICMP protocol.

sock_rdm//This type is rarely used and is not implemented on most operating systems, it is used to provide data link layers and does not guarantee packet order.

3. Public agreement

icmp//Internet Control Message Protocol, primarily used on gateways and hosts, in checking network status and reporting 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, he can ensure that the packet can reach the receiver, if an error occurs during transmission, it will resend the error packet

Third, the socket function

1, Socket_create

Function: Produces a socket that is equivalent to a data structure that produces a socket

Usage: socket_create (int domain,int type,int protocol)

Parameters: domai--protocol, type--type, protoco--public protocol

Returns: Sockets resource on success or false on error

2, Socket_bind

Role: Bind the socket to an IP address and port

Usage: Socket_bind (resource socket,string address [, int port])

Parameters: Socket--socket resource,address--ip address, port--Port

Return: Boolean

3, Socket_accept

Function: accepts a socket connection

Usage: socket_accept (Resource socket)

Parameters: Socket--socket Resource

Return: Return a new socket resource on success or false on error

4, Socket_connect

Function: Start a socket connection

Usage: Socket_connect (resource socket,string address [, int port])

Parameters: Socket--socket resource,address--ip address, port--Port

Return: Boolean

5, Socket_listen

Function: Listens for all connections by the specified socket

Usage: Socket_listen (resource socket [, int backlog])

Parameters: Socket--socket Resource

Return: Boolean

6, Socket_read

Function: Reads a specified length of data

Usage: Socket_read (resource socket,int length [, int type])

Parameters: Socket--socket resource,length--character length, type--php_binary_read| Php_normal_read

Returns: String

7, Socket_write

Function: Write data to socket

Usage: socket_write (resource socket,string buffer [, int length])

Parameters: Socket--socket resource,buffer--character, length--character length

Return: Boolean

8, Socket_send

Role: This function sends data to a connected socket

Usage: socket_send (resource socket,string buffer,int length,int flags)

Parameters: Socket--socket resource,buffer--character, length--character length

Return: Boolean

9, Socket_last_error

Function: Gets the last error code of the current socket

Usage: socket_last_error ([resource socket])

Parameters: Socket--socket Resource

return: int

10, Socket_strerror

Function: Returns a detailed error for the specified error number

Usage: socket_strerror (int errno)

Parameter: Errno--socket_last_error

Returns: String

11, Socket_close

Role: Close a socket resource

Usage: socket_close ([resource socket])

Parameters: Socket--socket Resource

return: null

Iv. PHP Open

Confirm opening the Socket method

Edit the php.ini file and remove the comments in front of the Extension=php_sockets.dll

Or

<?PHP Header ("Content-type:text/html;charset=utf-8"); if(!extension_loaded ('Sockets')) {if(Strtoupper (substr (Php_os,0,3)) =='WIN') {DL ('Php_sockets.dll'); printf ('Php_sockets.dll'); }Else{DL ('sockets.so'); printf ('sockets.so'); }}Else{printf ('Open with edit php.ini'); }

Five, the service side open "Here is a simple example, real and server interaction is more complex than this"

Function:

A. Initialize a socket and open a cache to send and receive data

B, wait for the connection, once a connection is generated, it will print "Socket connected" on the server-side screen

C, the server check the buffer, if there is data in the buffer, it will send data to the connected computer.

D, after the connection is closed, the server starts processing the next connection

<?PHP//Get Agreement$commonProtocol = Getprotobyname ('TCP'); //Create a socket$socket =socket_create (Af_inet, Sock_stream, $commonProtocol); //bind the socket to an IP address and portSocket_bind ($socket,'localhost',1337); //listens for all connections by the specified socket    Socket_listen ($socket); //Initialize buffer$buffer ="NO DATA";  while(true) {//accept a socket connection$connection =socket_accept ($socket); printf ("Socket connected\r\n"); //Detecting Buffer      if($buffer! ="") {printf ("Something is in the buffer...sending data...\r\n"); //write data to the socket cacheSocket_write ($connection, $buffer."\ r \ n"); printf ("wrote to socket\r\n"); }Else{printf ("No Data in the buffer\r\n"); }//reads data of a specified length       while($data = Socket_read ($connection,1024x768, Php_normal_read)) {$buffer=$data; //write data to the socket cacheSocket_write ($connection, $buffer."\ r \ n"); printf ("Buffer:". $buffer."\ r \ n"); }//close a socket resource      Socket_close ($connection); printf ("Closed the socket\r\n\r\n");}

Vi. Client Interaction

Function:

A, the client connects to the server, the client reads the data

<?PHP//Create socket$socket =socket_create (Af_inet, Sock_stream, sol_tcp); //Connecting Sockets$connection = Socket_connect ($socket,'localhost',1337); //reads data of a specified length     while($buffer = Socket_read ($socket,1024x768, Php_binary_read)) {if($buffer = ="NO DATA") {printf ("NO DATA");  Break; }Else{//Output Bufferprintf"Buffer Data:". $buffer.""); }} printf ("Writing to Socket"); //write data to the socket cache    if(!socket_write ($socket,"SOME data\r\n") {printf ("Write failed"); }//reads data of a specified length     while($buffer = Socket_read ($socket,1024x768, Php_normal_read)) {printf ("data sent Was:some data Response was:". $buffer.""); } printf ("Done Reading from Socket");

Simple example of PHP implementation socket

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.