PHP socket Basics

Source: Internet
Author: User
Tags ping and traceroute

◆ Socket Basics
PHP


Enable
Use the socket library of Berkley to create its connection. Socket is only a data structure. You use this socket data structure to start a meeting between the client and the server.
. This server is listening for preparing to generate a new session. When a client connects to the server, it opens a port on which the server is listening for a session. In this case, the server accepts
Connection Request. Now the client can send information to the server, and the server can also send information to the client.
To generate a socket, you need three variables: one protocol, one socket type, and one public protocol type. There are three protocols for generating a socket. You can continue to read the following content to obtain the detailed protocol content.
Defining a public protocol type is an essential element for connection. The following table shows the common protocol types.
Table 1: Protocols
Name/constant description
Af_inet: This is the majority of protocols used to generate sockets. It is transmitted over TCP or UDP and used for IPv4 addresses.
Af_inet6 is similar to the above, but it is used for IPv6 addresses.
Af_unix local protocol, used in UNIX andLinux


It is rarely used on the system. Generally, it is used when the client and server are on the same machine.
Table 2: Socket Type
Name/constant description
Sock_stream is a sequential, reliable, and complete byte stream-based connection. This is the most widely used socket type, which is transmitted over TCP.
Sock_dgram is a connectionless and fixed-length transmission call. The Protocol is unreliable and UDP is used for its connection.
Sock_seqpacket is a dual-line, reliable connection that sends fixed-length data packets for transmission. This package must be fully accepted before it can be read.
The socket type sock_raw provides a single network access, which uses the ICMP public protocol. (Ping and traceroute use this Protocol)
Sock_rdm is rarely used and is not implemented in most operating systems. It is provided to the data link layer and does not guarantee the packet sequence.
Table 3: Public protocols
Name/constant description
The ICMP Internet Control Message Protocol is mainly used on gateways and hosts to check network conditions and report error messages.
UDP user data packet protocol, which is a connectionless and unreliable transmission protocol
TCP transmission control protocol, which is the most reliable public protocol, ensures that the data packet can reach the receiver. If an error occurs during transmission, it resends the error data packet.
Now
After you know the three elements that generate a socket, we will use the socket_create () function in PHP to generate a socket. This
The socket_create () function requires three parameters: one protocol, one socket type, and one public protocol. The socket_create () function returns
The resource type that contains the socket. If it fails, false is returned.
Resourece socket_create (INT protocol, int sockettype, int commonprotocol );
Now you generate a socket. What then? PHP provides several functions to manipulate the socket. You can bind a socket to an IP address, listen to the communication of a socket, and accept a socket. Now let's look at an example to learn how the function generates, accepts, and listens to a socket.
<? PHP
$ Commonprotocol = getprotobyname ("tcp"); // obtain a protocol type using a public protocol name
$ Socket = socket_create (af_inet, sock_stream, $ commonprotocol); // an instance that generates a socket and returns a socket Resource
Socket_bind ($ socket, 'localhost', 1337); // bind the socket to the Local Computer
Socket_listen ($ socket); // listen to all incoming socket connections
// More socket functionality to come
?>
The above example generates your own server. The first line of the example,
$ Commonprotocol = getprotobyname ("TCP ");
Enable
Obtain a protocol type by using the public protocol name. TCP public protocol is used here. If you want to use UDP or ICMP, you should set getprotobyname ()
Change the function parameter to "UDP" or "ICMP ". Another optional method is to specify sol_tcp or sol_udp in
In the socket_create () function.
$ Socket = socket_create (af_inet, sock_stream, sol_tcp );
The second line of the example is the instance that generates a socket and returns a socket resource. After you have an instance with a socket resource, you must bind the socket to an IP address and a port.
Socket_bind ($ socket, 'localhost', 1337 );
Here you bind the socket to the local computer (127.0.0.1) and bind the socket to your port 1337. Then you need to listen to all incoming socket connections.
Socket_listen ($ socket );
After the fourth line, you need to understand all socket functions and their usage.
Table 4: Socket Functions
Function Name Description
Socket_accept () accepts a socket connection
Socket_bind () binds the socket to an IP address and port.
Socket_clear_error () clears socket errors or final errorsCode



Socket_close () closes a socket Resource
Socket_connect () starts a socket connection
Socket_create_listen () opens a socket listener on the specified port.
Socket_create_pair () generates a pair of identical sockets into an array.
Socket_create () generates a socket, which is equivalent to the data structure of a socket.
Socket_get_option () obtain the socket option
Socket_getpeername () obtains the IP address of a remote host similar to that of a remote host.
Socket_getsockname () gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scattered/aggregated Array
Socket_iovec_alloc () This function creates an iovec data structure that can send and receive read/write data.
Socket_iovec_delete () deletes an allocated iovec
Socket_iovec_fetch () returns the data of the specified iovec resource.
Socket_iovec_free () releases an iovec resource.
Socket_iovec_set () sets the new value of iovec data
Socket_last_error () obtains the final error code of the current socket.
Socket_listen () listens to all connections from the specified socket
Socket_read () reads data of the specified length
Socket_readv () reads data from scattered/aggregate Arrays
Socket_recv () ends data from the socket to the cache
Socket_recvfrom () accepts data from the specified socket. If no value is specified, the current socket is used by default.
Socket_recvmsg () receives messages from iovec
Socket_select () multi-path selection
Socket_send () This function sends data to the connected socket
Socket_sendmsg () sends a message to the socket
Socket_sendto () sends a message to the socket of the specified address
Socket_set_block () is set to block mode in socket
Set the socket in socket_set_nonblock () to non-block mode.
Socket_set_option () sets socket options
The socket_shutdown () function allows you to close the read, write, or specified socket
Socket_strerror () returns a detailed error of the specified error number
Socket_write () writes data to the socket Cache
Socket_writev () writes data to a distributed/aggregate Array
All the above functions are about socket in PHP. To use these functions, you must open your socket. If you do not open it, edit your php. INI file, remove the comments before the following line:
Extension = php_sockets.dll
If you cannot remove the annotation, use the following code to load the extension Library:
<? PHP
If (! Extension_loaded ('buckets ')){
If (strtoupper (substr (php_ OS, 3) = "win "){
DL ('php _ sockets. dll ');
} Else {
DL ('ets ETS. so ');
}
}
?>
If you do not know whether your socket is enabled, you can use the phpinfo () function to determine whether the socket is enabled. You can check the phpinfo information to check whether the socket is enabled.
View the socket information of phpinfo ().
◆ Generate a server
Now let's complete the first example. You need to listen to a specified socket and process user connections.
<? PHP
$ Commonprotocol = getprotobyname ("TCP ");
$ Socket = socket_create (af_inet, sock_stream, $ commonprotocol );
Socket_bind ($ socket, 'localhost', 1337 );
Socket_listen ($ socket );
// Accept any incoming connections to the server
$ Connection = socket_accept ($ socket );
If ($ connection ){
Socket_write ($ connection, "you have connected to the socket.../n/R ");
}
?>
You should use your command prompt to run this example. The reason is that a server is generated, not a Web page. If you try to use a web browser to run this script, it is likely to exceed 30 seconds. You can use the following code to set an unlimited running time, but we recommend that you use a command prompt to run it.
Set_time_limit (0 );
Perform a simple test on the script in your command prompt:
Php.exe example01_server.php
If you have not set the PHP interpreter in the system environment variable, you can specify the detailed path for php.exe. When you run this server, you can connect to port 1337 through remote login (Telnet) to test this server.

The preceding server has three problems: 1. It cannot accept multiple connections. 2. It only completes a unique command. 3. You cannot connect to this server through a web browser.
This first problem is easy to solve. You can use an application to connect to the server every time. However, the problem is that you need to use a web page to connect to the server, which is more difficult. You can make your server accept the connection and then send some data to the client (if it must be written), close the connection and wait for the next connection.
Make improvements based on the previous Code and generate the following code for your new server:
<? PHP
// Set up our socket
$ Commonprotocol = getprotobyname ("TCP ");
$ Socket = socket_create (af_inet, sock_stream, $ commonprotocol );
Socket_bind ($ socket, 'localhost', 1337); // socket_bind () binds the socket to an IP address and port.
Socket_listen ($ socket );
// Initialize the buffer
$ Buffer = "no data ";
While (true ){
// Accept any connections coming in on this socket
$ Connection = socket_accept ($ socket); // socket_accept () accepts a socket connection
Printf ("Socket connected/R/N ");
// Check to see if there is anything in the buffer
If ($ buffer! = ""){
Printf ("something is in the buffer... sending data.../R/N ");
Socket_write ($ connection, $ buffer. "/R/N"); // socket_write () write data to the socket Cache
Printf ("wrote to socket/R/N ");
} Else {
Printf ("no data in the buffer/R/N ");
}
// Get the input
While ($ DATA = socket_read ($ connection, 1024, php_normal_read) // socket_read () reads data of the specified length
{
$ Buffer = $ data;
Socket_write ($ connection, "information stored ED/R/N ");
Printf ("buffer:". $ buffer. "/R/N ");
}
Socket_close ($ connection); // socket_close () close a socket Resource
Printf ("closed the socket/R/n/R/N ");
}
?>
This
What should I do on a server? It initializes a socket and opens a cache to send and receive data. It waits for the connection. Once a connection is generated, it prints "Socket
Connected is displayed on the server screen. This server checks the buffer zone. If there is data in the buffer zone, it sends the data to the connected computer. Then it sends the receiving message of the data.
Information, once it accepts the information, it will save the information to the data, and let the connected computer know the information, and finally close the connection. When the connection is closed, the server starts to process the next connection.
◆ Generate a client
It is easy to handle the second problem. You need to generate a PHP page to connect to a socket, send some data to its cache, and process it. Then you have a processed data record, and you can send your data to the server. Connect to another client and it will process the data.
The following example demonstrates the use of socket:
<? PHP
// Create the socket and connect
$ Socket = socket_create (af_inet, sock_stream, sol_tcp );
$ Connection = socket_connect ($ socket, 'localhost', 1337 );
While ($ buffer = socket_read ($ socket, 1024, php_normal_read )){
If ($ buffer = "no data "){
Echo ("<p> no data </P> ");
Break;
} Else {
// Do something with the data in the buffer
Echo ("<p> buffer data:". $ buffer. "</P> ");
}
}
Echo ("<p> writing to socket </P> ");
// Write some test data to our socket
If (! Socket_write ($ socket, "Some data/R/N ")){
Echo ("<p> write failed </P> ");
}
// Read any response from the socket
While ($ buffer = socket_read ($ socket, 1024, php_normal_read )){
Echo ("<p> data sent was: Some data <br> response was:". $ buffer. "</P> ");
}
Echo ("<p> done reading from socket </P> ");
?>
This
The example code demonstrates how the client connects to the server. The client reads data. If this is the first connection to reach this loop, the server will send "No
"Data" is returned to the client. If this happens, the client is connected. The client sends its data to the server, and the data is sent to the server. The client waits for a response. Once the response is received
It writes the response to the screen.

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.