Source: http://blog.csdn.net/heiyeshuwu/archive/2005/08/16/456000.aspx
[Translation] PHP and Socket
Article: PHP and Socket
Title: PhP game programming
Author: Matt rutledget
Translation: heiyeluren
◇ Socket Basics
◇ Generate a server
◇ Generate a client
In this chapter, you will understand the fascinating and confusing socket (sockets ). 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/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.