Finally, edit the charming and confusing socket (Sockets) of jguon ). Sockets is not fully utilized in PHP. Today, you will see a server that can connect to the client and connect to the client using socket. The server sends detailed processing information to the client.
When you see the complete socket process, you will use it in future program development. This server is an HTTP server that allows you to connect to, and the client is a Web browser, which is a single client/server relationship.
◆ Socket Basics
PHP uses the Berkley socket library to create its connection. 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 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. At this time, the server accepts the client connection request, then a loop is performed. 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.
The AF_UNIX local protocol is rarely used on Unix and Linux systems. It is generally used when the client and server are on the same server and on the same server.
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 data 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 that you know the three elements that generate a socket, we will use the socket_create () function in php to generate a socket. The socket_create () function requires three parameters: one protocol, one socket type, and one public protocol. If the socket_create () function runs successfully, a resource type containing socket is returned. If the function 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 ");
$ Socket = socket_create (AF_INET, SOCK_STREAM, $ commonProtocol );
Socket_bind ($ socket, 'localhost', 1337 );
Socket_listen ($ socket );
// More socket functionality to come
?>
The above example generates your own server. The first line of the example,
$ CommonProtocol = getprotobyname ("tcp ");
Use the public protocol name to obtain a protocol type. TCP public protocol is used here. If you want to use UDP or ICMP, 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 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 the final error code
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
(Note: The function introduction deletes some of the original content. For more information about function usage, see the original English text or the PHP manual)
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. For example:
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. For example:
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_listen ($ socket );
// Initialize the buffer
$ Buffer = "no data ";
While (true)
{
// Accept any connections coming in on this socket
$ Connection = socket_accept ($ socket );
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 ");
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 stored ed \ r \ n ");
Printf ("Buffer:". $ buffer. "\ r \ n ");
}
Socket_close ($ connection );
Printf ("Closed the socket \ r \ n ");
}
?>
What does this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection. Once a connection is generated, it prints "Socket connected" 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 information of the Data. Once it accepts the information, it stores the information in the data, allows the connected computer to know the information, and closes the connection. When the connection is closed, the server starts to process the next connection. (For poor translation, attach the original article)
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 takes es information it stores
It in the data, lets the connected computer know that it has stored ed 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 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 another processed data, and you can send your data to the server. Connect to another client and it will process the data.
To solve the second problem is very easy. You need to create a PHP page that connects
A socket, receive any data that is in the buffer, and process it. After you have processed
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:
<? Php
// Create the socket and connect
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP );
$ Connection = socket_connect ($ socket, 'localhost', 1337 );
While ($ buffer = fig ($ 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 = fig ($ 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 in this example demonstrates how to connect the client to the server. The client reads data. If this is the first connection to reach this loop, the server will send "no data" 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 a response is received, it writes the response to the screen.
Tank wars combined with Socket
(Because it is used to describe the combination of the game and socket, it is not very relevant to this article, so it is not translated, it is recommended to refer to the original English)
[Digression]
The original intention of the translation article is that I am personally very interested in socket, and currently there are few articles in php in China, except for some of the content in the php manual, so after I read the socket content in the book "PHP Game Programming", I decided to translate the content. I know that the quality of the translation is not good. Please forgive me.
In addition, I also found that the Socket content in Core PHP Programming Third Edition is good. If I have time, I think I may also translate it. This is the first time I have translated an article. It took me nearly five hours to translate it. It may be a hundred errors. If the translation is unreasonable, please forgive me. If you are interested in improving this content, please send me an email. In the early hours of the morning, I was unable to sleep. I don't know if I was in another corner, and some people were like me.
I hope this article will help you with PHP Socket programming. Thank you for reading this article.