In-depth explanation and example analysis of PHP socket _php skills

Source: Internet
Author: User
Tags phpinfo set socket socket error

In this chapter you will learn about attractive and confusing sockets (Sockets). Sockets is a feature that is not fully exploited in PHP. Today you will see the creation of a server that can use a client-side connection and connect using a socket on the client, and the server will send detailed processing information to the client.
When you see the full socket process, you will use it later in the program development. This server is an HTTP server that lets you connect, the client is a Web browser, this is a single client/server relationship.

Socket Basics
PHP uses the Berkley socket library to create its connection. You can see that the socket is nothing more than a data structure. You use this socket data structure to start a session between the client and the server. This server is always listening to prepare to generate a new session. When a client connects to the server, it opens a session on a port on which the server is listening. At this point, the server side accepts the client's connection request, and then a loop is made. Now the client is able to send information to the server, and the server can send messages to the client.
To produce a socket, you need three variables: a protocol, a socket type, and a common protocol type. There are three protocols available for a socket to choose from, and continue to look at the content below to get detailed protocol content.
Defining a common protocol type is an essential element for a connection. The following table looks at the types of common protocols that we have.

Table I: Agreement
Name/Constant Description
Af_inet This is most of the protocol used to generate sockets, using TCP or UDP for transmission, used in IPV4 addresses
Af_inet6 is similar to the above, but is used in IPV6 address
Af_unix local protocols, used on UNIX and Linux systems, are rarely used, typically when the client and server are on the same platform

Table II: Socket type
Name/Constant Description
Sock_stream This protocol is a sequential, reliable, data-complete, byte-stream based connection. This is the most commonly used socket type, which is transmitted using TCP.
Sock_dgram This protocol is connectionless, fixed-length transmission calls. The protocol is unreliable and uses UDP to connect to it.
Sock_seqpacket This protocol is a two-way, reliable connection that sends fixed-length packets for transmission. This package must be fully accepted for reading.
Sock_raw This socket type provides a single network access, this socket type uses 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 packet order

Table III: Public agreements
Name/Constant Description
ICMP Internet Control Message Protocol, used primarily on gateways and hosts to check network conditions and report error messages
UDP User Data Packet protocol, which is a connectionless, unreliable transmission protocol
TCP Transmission Control Protocol, this is a reliable public protocol with the most use, it can ensure that the packet can reach the recipient, if there is an error in the transmission process, it will resend the error packet.

Now that you know the three elements that produce a socket, then we use the Socket_create () function in PHP to produce a socket. This socket_create () function requires three parameters: a protocol, a socket type, and a public protocol. The Socket_create () function successfully returns a resource type containing the socket, or false if it does not succeed.
Resourece socket_create (int protocol, int sockettype, int commonprotocol);

Now you have a socket, and then what? PHP provides several functions for manipulating sockets. You can bind a socket to an IP, listen for a socket, and accept a socket; Now let's look at an example of how a function generates, accepts, and listens to a socket.

Copy Code code as follows:

<?php
$commonProtocol = Getprotobyname ("TCP");
$socket = Socket_create (Af_inet, Sock_stream, $commonProtocol);
Socket_bind ($socket, ' localhost ', 1337);
Socket_listen ($socket);
More sockets functionality to come
?>

This example above generates a server side of your own. Example the first line,
$commonProtocol = Getprotobyname ("TCP");
Use the public protocol name to obtain a protocol type. The TCP public protocol is used here, and if you want to use UDP or ICMP protocol, you should change the parameter of the Getprotobyname () function to "UDP" or "ICMP." Another option is to specify SOL_TCP or SOL_UDP in the socket_create () function instead of using the Getprotobyname () function.
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp);
The second line of the example is the instance that produces a socket and returns a socket resource. After you have an instance of 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 1337 port. Then you'll need to listen for all incoming socket connections.
Socket_listen ($socket);
After line fourth, you'll need to know all the socket functions and their usage.

table four: 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 the socket error or the last error code
Socket_close () closes a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () opens a socket listener on the specified port
Socket_create_pair () produces a pair of indistinguishable sockets into an array
Socket_create () produces a socket, which is equivalent to generating a socket data structure
Socket_get_option () Get socket option
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () adds a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure capable of sending and receiving read and write
Socket_iovec_delete () deletes an already allocated Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () frees a Iovec resource
Socket_iovec_set () sets the Iovec data new value
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 coming from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket and, if not specified, the default current socket
Socket_recvmsg () received a message from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends 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 () is set to block mode in the socket
Socket_set_nonblock () socket is set to not block mode
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

(Note: The function of the introduction of the deletion of some of the original content, the function of the detailed use of recommendations to refer to the original English, or reference PHP manual)
All of the above functions are PHP about sockets, using these functions, you have to open your socket, if you do not open, please edit your php.ini file, remove the following line of comments:
Extension=php_sockets.dll
If you cannot remove the annotation, use the following code to load the extension library:

Copy Code code as follows:

<?php
if (!extension_loaded (' Sockets '))
{
if (Strtoupper (substr (Php_os, 3)) = = "WIN")
{
DL (' Php_sockets.dll ');
}
Else
{
DL (' sockets.so ');
}
}
?>

If you don't know if your socket is open, you can use the Phpinfo () function to determine if the socket is open. You see if the socket is open by looking at the Phpinfo information. The following figure:
View Phpinfo () information about the socket

Create a server
Now let's make the first example perfect. You need to listen for a specified socket and handle the user's connection.

Copy Code code as follows:

<?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 this will produce a server instead of a Web page. If you try to run the script using a Web browser, chances are that it will exceed the 30-second limit. You can use the following code to set an unlimited run time, but it is recommended that you use a command prompt to run.
set_time_limit (0);
Do a simple test of this script at your command prompt:
Php.exe example01_server.php
If you do not set the path of the PHP interpreter in the system's environment variables, you will need to specify a detailed path to the Php.exe. When you run this server side, you can connect to the port 1337来 by remote login (telnet) to test the server. The following figure:

There are three problems with the server side above:
1. It cannot accept multiple connections.
2. It completes only one command.
3. You cannot connect to this server through a Web browser.
This first question is easier
To resolve, you can use an application to connect to the server each time. But the problem is that you need to use a Web page to connect to the server, which is more difficult. You can have your server accept the connection, and then some data to the client (if it must be written), close the connection and wait for the next connection.
On the basis of the previous code, the following code is created to do your new server side:

Copy Code code as follows:

<?php
Set up our sockets
$commonProtocol = Getprotobyname ("TCP");
$socket = Socket_create (Af_inet, Sock_stream, $commonProtocol);
Socket_bind ($socket, ' localhost ', 1337);
Socket_listen ($socket);
Initialize the buffer
$buffer = "NO DATA";
while (true)
{
Accept any connections coming with this socket

$connection = Socket_accept ($socket);
printf ("Socket connected\r\n");
Check to the If there are anything in the buffer
if ($buffer!= "")
{
printf ("Something is in the buffer...sending data...\r\n");
Socket_write ($connection, $buffer. "\ r \ n");
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))
{
$buffer = $data;
Socket_write ($connection, "Information received\r\n");
printf ("Buffer:"). $buffer. "\ r \ n");
}
Socket_close ($connection);
printf ("Closed the socket\r\n\r\n");
}
?>


What does this server side do? It initializes a socket and opens a cache to send and receive data. It waits for a connection, and once it produces a connection, it prints "Socket connected" on the server-side screen. This server checks the buffer, and if there is data in the buffer, it sends the data to the connected computer. It then sends the acceptance information for this data, and once it accepts the information, it saves the information to the data and lets the connected computer know the information, and then closes the connection. When the connection is closed, the server starts processing the next connection again. (bad translation, attached to the original text)
This is what the server does. It initializes the socket and the buffer
and send data. Then it waits for a connection. Once A connection is created it prints ' Socket connected ' to the ' screen the ' is running on. The server then checks to if
There is anything in the buffer; If there is, it sends the data to the connected computer.
After it sends the data it waits to receive information. Once It receives information it stores
It in the data, lets the connected computer know, it has received the information, and
Then closes the connection. After the connection is closed, the server starts the whole
Process again.

Generate a Client
It is easy to deal with the second question. You need to generate a PHP page to connect a socket, send some data into it's cache and process it. Then you have to deal with the data after the Dayton, you can send your data to the server. On a different client connection, it will process those data.
To solve the second problem are very easy. You are need to create a PHP page which connects to
A socket, receive any data of this is in the buffer, and process it. After you have processed the
Data in the ' buffer ' can send your data to the server. When another client connects, it
'll process the data you sent and the client would send more data back to the server.

The following example demonstrates the use of sockets:

Copy Code code as follows:

<?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 sockets
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>");
?>

The code for this example demonstrates that the client connects to the server. The client reads the data. If this is the first time a connection is reached for this loop, the server will send "NO DATA" back to the client. If this happens, the client is on top of the connection. 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 received, it will write 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.