How PHP implements the socket

Source: Internet
Author: User
This article is mainly to share with you how to implement the socket PHP method, mainly in the text and code to share with you, hope to help everyone.

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 a server, it opens a session on a port that the server is listening on.
4, the server side accepts the client connection 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.

Second, the Socket variable
To generate a socket, you need three variables: a protocol, a socket type, and a common protocol type.

1. Agreement

View source Copy to Clipboard printing help

    1. Af_inet

    2. The protocol that generates the socket, which is transmitted using TCP or UDP, with the address of the IPV4

    3. Af_inet6

    4. The protocol that generates the socket, which is transmitted using TCP or UDP, with the address of the IPV6

    5. Af_unix

    6. Local protocols, 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

View source Copy to Clipboard printing help

    1. Sock_stream

    2. This protocol is a sequential, reliable, data-complete byte-stream-based connection. This is the most used socket type, which is transmitted using TCP.

    3. Sock_dgram

    4. This protocol is a non-connected, fixed-length transfer call. The protocol is unreliable and uses UDP to connect to it.

    5. Sock_seqpacket

    6. 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.

    7. Sock_raw

    8. This socket type provides a single network access, and this socket type uses the ICMP public protocol. (Ping, traceroute Use this Protocol)

    9. Sock_rdm

    10. 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 packet order

3. Public agreement

View source Copy to Clipboard printing help

    1. Icmp

    2. Internet Control Message Protocol, primarily used on gateways and hosts, to check network conditions and report error messages

    3. Udp

    4. User data message protocol, which is a non-connected, unreliable transport protocol

    5. Tcp

    6. 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.

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: domain, protocol; type, type; protocol, public Protocol
Return: Socket 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, ports
return: Boolean

3, Socket_accept
Function: accepts a socket connection
Usage: socket_accept (Resource socket)
Parameters: Socket,socket Resource
Returns: Returns 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, ports
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 the socket cache
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 buf, int len, int flags)
Parameters: Socket,socket resource;buf, character; Len, 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 no;
Returns: String

11, Socket_close
Role: Close a socket resource
Usage: socket_close ([resource socket])
Parameters: Socket,socket resource;
return: null

Iv. Description of Use
Confirm opening the Socket method
A, edit the php.ini file, remove the comments before Extension=php_sockets.dll:
B, code to load the extension library

View source Copy to Clipboard printing help

    1. if (!extension_loaded (' sockets ')) {

    2. if (Strtoupper (substr (php_os, 0, 3) = = = "WIN") {

    3. DL (' Php_sockets.dll ');

    4. }else{

    5. DL (' sockets.so ');

    6. }

    7. }

Five, Socket programming

1. Server-side

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 checks the buffer, if there is data in the buffer, it will send the data to the connected computer.
It then sends the receiving information of the data, and once it accepts the information, it saves the information to the data and lets the connected computer know the information and finally closes the connection.

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

View source Copy to Clipboard printing help

  1. Get protocol $commonProtocol = Getprotobyname ("TCP");    Generate a socket $socket = Socket_create (Af_inet, Sock_stream, $commonProtocol);     Bind the socket to an IP address and port Socket_bind ($socket, ' localhost ', 1337);    Listens for all connections Socket_listen ($socket) by the specified socket;  Initialize buffer $buffer = "NO DATA";      while (true) {//accepts a socket connection $connection = Socket_accept ($socket);        printf ("Socket connected\r\n");          Detects the buffer if ($buffer! = "") {printf ("Something is in the buffer...sending data...\r\n"); Write data to the socket cache Socket_write ($connection, $buffer.          "\ r \ n");      printf ("wrote to socket\r\n");      }else {printf ("No Data in the buffer\r\n");          }//Reads data of the specified length while ($data = Socket_read ($connection, 1024x768, Php_normal_read)) {$buffer = $data;          Write data to the socket cache Socket_write ($connection, "Information received\r\n"); printf ("Buffer:".) $buffer.      "\ r \ n"); }//Close a Socket resource Socket_close ($coNnection);  printf ("Closed the socket\r\n\r\n"); }

2, the Client

Function:
A, the client connects to the server. The client reads the data.

B, if this is the first time to reach the first connection to the loop, the server will send "NO DATA" back to the client. If this happens, the client is on top of the connection.

C, the client sends its data to the server, the data is sent to the server, and the client waits for a response. Once the response is accepted, it writes the response to the screen.

View source Copy to Clipboard printing help

    1. //created    Socket $socket = Socket_create (Af_inet, Sock_stream, sol_tcp);    Link Socket $connection = socket_connect ($socket, ' localhost ', 1337); Reads the specified length of data while ($buffer = Socket_read ($socket, 1024x768, php_normal_read)) {if ($buffer = = "NO DATA") {print          F ("NO DATA");      Break }else{//Output buffer printf ("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 the specified length while ($buffer = Socket_read ($socket, 1024x768, php_normal_read)) {printf ("Data sent Was:some data Resp Onse was: ". $buffer.  "");
      } printf ("Done Reading from 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.