Home >Backend Development >PHP Tutorial >PHP socket explanation and examples_PHP tutorial
Final edit jguon's fascinating and confusing Sockets. Sockets are an underutilized feature in PHP. Today you will see how to generate a server that can use the client connection, and use the socket on the client to connect, and the server will send detailed processing information to the client.
When you see the complete socket process, you will use it in future program development. The server is an HTTP server that allows you to connect, and the client is a web browser. This is a single client/server relationship.
◆ Socket Basics
PHP uses Berkley's socket library to create its connections. You can know that socket is just a data structure. You use this socket data structure to start a session between the client and the server. This server is always listening and 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. At this time, the server accepts the client's connection request and then performs a cycle. Now the client can send information to the server, and the server can send information to the client.
To generate a Socket, you need three variables: a protocol, a socket type, and a public protocol type. There are three protocols to choose from when generating a socket. Continue reading below to get detailed protocol content.
Defining a public protocol type is an essential element of connection. In the table below we take a look at the common protocol types.
Table 1: Agreement
Name/Constant Description
AF_INET This is the protocol used by most sockets, using TCP or UDP for transmission, and is used in IPv4 addresses
AF_INET6 is similar to the above, but it is used for IPv6 addresses
AF_UNIX Local protocol, used on Unix and Linux systems. It is rarely used. It is usually used when the client and server are on the same machine
Table 2: Socket type
Name/Constant Description
SOCK_STREAM This protocol is a sequential, reliable, data-integrated byte stream-based connection. This is the most commonly used socket type. This socket uses TCP for transmission.
SOCK_DGRAM This protocol is a connectionless, fixed-length transfer call. This protocol is unreliable and uses UDP for its connections.
SOCK_SEQPACKET This protocol is a dual-line, reliable connection that sends fixed-length data packets for transmission. This package must be accepted completely before it can be read.
SOCK_RAW This socket type provides single network access. This socket type uses the ICMP public protocol. (ping and 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 and does not guarantee the order of data packets
Table 3: Public Protocol
Name/Constant Description
ICMP Internet Control Message Protocol, mainly used on gateways and hosts to check network conditions and report error messages
UDP User Datagram Protocol, it is a connectionless, unreliable transmission protocol
TCP Transmission Control Protocol, which is the most commonly used reliable public protocol, can ensure that the data packet can reach the recipient. If an error occurs during the transmission process, it will resend the error packet.
Now that you know the three elements that generate a socket, we use the socket_create() function in PHP to generate a socket. This socket_create() function requires three parameters: a protocol, a socket type, and a public protocol. The socket_create() function returns a resource type containing the socket if it succeeds, or false if it fails.
Resourece socket_create(int protocol, int socketType, int commonProtocol);
Now you create a socket, then what? PHP provides several functions for manipulating sockets. You can bind a socket to an IP, listen to a socket's communication, and accept a socket; now let's look at an example to understand how the function generates, accepts, and listens to a socket.
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, ‘localhost’, 1337);
socket_listen($socket);
// More functionality socket to come
?>
The above example generates your own server side. The first line of the example,
$commonProtocol = getprotobyname(“tcp”);
Use the public protocol name to get a protocol type. The TCP public protocol is used here. If you want to use UDP or ICMP protocol, then you should change the parameters of the getprotobyname() function to "udp" or "icmp". Another alternative 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 creates a socket and returns an instance of the socket resource. After you have an instance of the 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 need to listen for all incoming socket connections.
socket_listen($socket);
After the fourth line, you need to understand all socket functions and their usage.
Table 4: Socket function
Function name Description
socket_accept() Accept a Socket connection
socket_bind() Bind the socket to an IP address and port
socket_clear_error() Clear socket error or last error code
socket_close() Close a socket resource
socket_connect() Start a socket connection
socket_create_listen() Open a socket listening on the specified port
socket_create_pair() Generates a pair of indistinguishable sockets into an array
socket_create() Generates a socket, which is equivalent to generating a socket data structure
socket_get_option() Get socket options
socket_getpeername() Get the IP address of a remote similar host
socket_getsockname() Get 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 an iovec data structure that can send, receive, read and write
socket_iovec_delete() Delete an allocated iovec
socket_iovec_fetch() Returns the data of the specified iovec resource
socket_iovec_free() Release an iovec resource
socket_iovec_set() Set the new value of iovec data
socket_last_error() Get the last error code of the current socket
socket_listen() Listens to all connections from the specified socket
socket_read() Read data of specified length
socket_readv() Read data from scattered/aggregated array
socket_recv() Finish data from socket to cache
socket_recvfrom() accepts data from the specified socket. If not specified, it defaults to the current socket
socket_recvmsg() Receive messages from iovec
socket_select() Multiple selection
socket_send() This function sends 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 to block mode in socket
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() Set socket options
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() Returns the detailed error of the specified error number
socket_write() Write data to socket cache
socket_writev() Write data to scatter/aggregate array
(Note: The function introduction has deleted part of the original text. It is recommended to refer to the original English text for detailed use of the function, or refer to the PHP manual)
All the above functions are about sockets in PHP. To use these functions, you must open your socket. If you have not opened it, please edit your php.ini file and remove the comment in front of the following line:
extension=php_sockets.dll
If you cannot remove the comment, please use the following code to load the extension library:
if(!extension_loaded(‘sockets’))
{
if(strtoupper(substr(PHP_OS, 3)) == “WIN”)
{
dl(‘php_sockets.dll’);
}
else
{
dl(‘sockets.so’);
}
}
?>
If you don't know whether your socket is open, you can use the phpinfo() function to determine whether the socket is open. You can check whether the socket is open by checking the phpinfo information. As shown below:
View phpinfo() information about socket
◆ Generate a server
Now let's improve the first example. You need to listen to a specific socket and handle user connections.
$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...nr");
}
?>
You should use your command prompt to run this example. The reason is because a server will be generated here, not a Web page. If you try to run this script using a web browser, there's a good chance it will exceed the 30-second limit. You can use the code below to set an infinite run time, but it is recommended to use the command prompt to run.
set_time_limit(0);
Simply test this script in your command prompt:
Php.exe example01_server.php
If you have not set the path to the php interpreter in your system's environment variables, then you will need to specify the path to php.exe. When you run the server, you can test the server by connecting to port 1337 via telnet. As shown below:
There are three problems with the server side above: 1. It cannot accept multiple connections. 2. It only completes one command. 3. You cannot connect to this server through a web browser.
This first problem is easier to solve, you can use an application to connect to the server every time. But the next 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, write some data to the client (if it must write it), close the connection and wait for the next connection.
Improve on the previous code and generate the following code to make your new server:
// Set up our socket
$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 in on this socket
$connection = socket_accept($socket);
printf("Socket connectedrn");
// Check to see if there is anything in the buffer
if($buffer != "")
{
Printf("Something is in the buffer...sending data...rn");
socket_write($connection, $buffer . "rn");
Printf("Wrote to socketrn");
}
else
{
Printf("No Data in the bufferrn");
}
// Get the input
while($data = socket_read($connection, 1024, PHP_NORMAL_READ))
{
$buffer = $data;
socket_write($connection, "Information Receivedrn");
Printf("Buffer: " . $buffer . "rn");
}
socket_close($connection);
printf("Closed the socketrnrn");
}
?>
What should this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection and once a connection is made it prints "Socket connected" on the screen on the server side. This server checks the buffer and if there is data in the buffer, it sends the data to the connected computer. Then it sends an acceptance message for this data. Once it accepts the message, it saves the message to the data, makes the connected computer aware of the message, and finally closes the connection. When the connection is closed, the server starts processing the next connection. (The translation is bad, the original text is attached)
This is what the server does. It initializes the socket and the buffer that you use to receive
and send data. Then it waits for a connection. Once a connection is created it prints “Socket connected” to the screen the server is running on. The server then checks to see 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 that 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
Dealing with the second problem is easy. You need to generate a php page, connect to a socket, send some data to its cache and process it. Then after you have processed the data, you can send your data to the server. On another client connection, it will process that data.
To solve the second problem is very easy. You need to create a PHP page that connects to
a socket, receive any data that is in the buffer, and process it. After you have processed the
data in the buffer you can send your data to the server. When another client connects, it
will process the data you sent and the client will send more data back to the server.
The following example demonstrates the use of socket:
// 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(“
NO DATA
”);Buffer Data: “ . $buffer . “
”);Writing to Socket
”);Write failed
”);Data sent was: SOME DATA
Response was:” . $buffer . “
Done Reading from Socket
”);This example code demonstrates the client connecting to the server. The client reads the data. If this is the first connection to arrive in 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 writes the response to the screen.
Tank battle combined with Socket
(Because it describes the combination of games and sockets, it has little connection with this article, so it will not be translated. It is recommended to refer to the original English text)
[Digression]
The original intention of translating the article is because I am personally very interested in sockets, and there are currently relatively few articles on PHP in China, except for some content in the PHP manual, so I read the book "PHP Game Programming" about sockets. After reading the content, I decided to translate it. I know that the quality of the translation is not good, so please forgive me.
In addition, I also found that the Socket content in "Core PHP Programming" Third Edition is pretty good. If I have time, I think maybe I will translate it. This is my first time to translate an article. It took me nearly five hours. The article can be said to be full of errors. Please forgive me if the translation is unreasonable. If you are interested in improving this content, you can send me an email. This early in the morning, I couldn't sleep. I wonder if there are people in other corners like me.
I hope this article can give some help to friends who want to learn PHP Socket programming. Thank you for reading this article full of errors