PHP socket Tutorials and Examples _php tutorial

Source: Internet
Author: User
Tags learn php set socket socket error
The final editor Jguon charming and confusing sockets (Sockets). Sockets is a feature that is not fully utilized in PHP. Today you will see a server that can use a client connection, and the client uses a socket to connect to it, and 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, 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 tell that the socket is just a data structure. You use this socket data structure to start a session between a client and a server. This server is always listening ready to produce a new session. When a client connects to a server, it opens a session on a port that the server is listening on. At this point, the server accepts the client's connection request, then it loops. Now the client is able to send messages to the server, and the server can send messages to the client.
To generate a socket, you need three variables: a protocol, a socket type, and a common protocol type. Generate a socket there are three protocols to choose from, and continue to look at the content below to get a detailed agreement.
Defining a common protocol type is an essential element for connecting. The table below let's look at the types of protocols that are public.

Table I: Protocol
Name/Constant Description
Af_inet This is most of the protocol used to generate sockets, using TCP or UDP for transmission, used in IPV4 address
Af_inet6 similar to the above, but to use the address of IPV6
Af_unix local protocols, used on UNIX and Linux systems, are rarely used, and are typically used when the client and server are on the same platform and on
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 used socket type, which is transmitted using TCP.
Sock_dgram This protocol is a non-connected, fixed-length transfer call. The protocol is unreliable and uses UDP to connect to it.
Sock_seqpacket This protocol is a dual-line, reliable connection that sends a fixed-length packet for transmission. This package must be fully accepted to be read.
Sock_raw This socket type provides a single network access, this socket type uses the 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 to use, does not guarantee the order of packets

Table III: Public agreements
Name/Constant Description
ICMP Internet Control Message Protocol, primarily used on gateways and hosts, to check network conditions and report error messages
UDP user Data message protocol, which is a non-connected, unreliable transport protocol
TCP Transmission Control Protocol, which is a reliable public agreement with the most use, guarantees that packets will reach the recipient, and if an error occurs during transmission, it retransmits the error packet.

Now that you know the three elements that produce a socket, we use the socket_create () function in PHP to generate a socket. This socket_create () function requires three parameters: one protocol, one socket type, and one public protocol. The Socket_create () function successfully returns a resource type that contains the socket and returns 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 to manipulate the socket. You can bind a socket to an IP, listen to a socket for communication, and accept a socket; Now let's look at an example of how a function generates, receives, 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 sockets functionality to come
?>


The above example produces a server-side of your own. The first line of the example,
$commonProtocol = Getprotobyname ("TCP");
Use the public protocol name to obtain a protocol type. Here is the TCP public protocol, if you want to use UDP or ICMP protocol, then you should change the Getprotobyname () function parameter to "UDP" or "ICMP". An alternative 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 to produce a socket and return an instance of the 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 need to listen for all incoming socket connections.
Socket_listen ($socket);
After line fourth, you need to know all the socket functions and their use.

Table IV: Socket function
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 () Close a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () Open a socket listener on the specified port
Socket_create_pair () produces a pair of indistinguishable sockets into an array
Socket_create () produces a socket equivalent to a data structure that produces a socket
Socket_get_option () Get socket options
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write
Socket_iovec_delete () Delete an already assigned Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () releasing a Iovec resource
Socket_iovec_set () Sets the new data value of the Iovec
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 from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket
Socket_recvmsg () receive messages from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends the 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 () set as block mode in socket
Socket_set_nonblock () set to non-block mode in socket
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 introduces the deletion of part of the original content, the function of the detailed use of the proposed reference to the original English, or reference PHP manual)


All of the above functions are in PHP for the socket, using these functions, you must open your socket, if you do not open, please edit your php.ini file, remove the following line before the comment:
Extension=php_sockets.dll
If you cannot remove the comment, 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 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. Such as:

View Phpinfo () information about the socket


Generate a server


Now let's refine the first example. You need to listen for a specified socket and process the user's connection.

$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 had connected to the socket...\n\r");
}
?>

You should use your command prompt to run this example. The reason is because there will be a server, not a Web page. If you try to run the script using a Web browser, it is likely 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 run it using the command prompt.
Set_time_limit (0);
Make a simple test of the script at your command prompt:
Php.exe example01_server.php
If you do not set the path to the PHP interpreter in the system's environment variables, you will need to specify a detailed path for the Php.exe. When you run this server side, you can connect to the port 1337来 by remote login (telnet) to test the server. Such as:


The server side above has three questions: 1. It cannot accept multiple connections. 2. It only completes a single 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 problem behind it is that you need to use a Web page to connect to the server, which is a bit more difficult. You can let 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.
To build on the previous code, generate the following code to do your new server side:

!--? php
//Set up and 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" this socket

$connection = socket_accept ($socket);
printf ("Socket connected\r\n");
//Check to see 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, 1024x768, php_normal_read))
{
$buffer = $data;
Sock Et_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 a connection is generated it will print "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 receiving information of the data, and once it accepts the information, it saves the information to the data and lets the connected computer know the information and finally closes the connection. When the connection is closed, the server starts processing the next connection. (the translation is rotten, enclose the original text)
This is what the server does. It initializes the socket and the buffer that is the use to receive
and send data. Then it waits for a connection. Once A connection is created it prints "Socket connected" to the screen of 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
The 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

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


The following example demonstrates the use of a 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, 1024x768, Php_normal_read))
{
if ($buffer = = "NO DATA")
{
Echo ("

NO DATA

”);
Break
}
Else
{
Do something with the data in the buffer
Echo ("

Buffer Data: ". $buffer. “

”);
}
}
Echo ("

Writing to Socket

”);
Write some test data to our socket
if (!socket_write ($socket, "SOME data\r\n"))
{
Echo ("

Write failed

”);
}
Read any response from the socket
while ($buffer = Socket_read ($socket, 1024x768, Php_normal_read))
{
Echo ("

Data sent Was:some data
Response was: ". $buffer. “

”);
}
Echo ("

Done Reading from Socket

”);
?>

The code for this example shows the client connecting 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 accepted, it writes the response to the screen.


Tank battles combined with sockets

(because it is a description of the game and socket combination, with this article is not very contact, so do not translate, recommended reference to the original English)


[Off Topic]

The original intention of the article is because I am very interested in the socket, and at present there are few PHP articles in the country, in addition to the PHP manual part of the content, so I read the "PHP Game Programming" This book has about the contents of the socket decided to translate, I know the quality of translation is not good, please forgive me.

In addition, I in "Core PHP Programming" Third edition also found inside the socket content is good, if available, I think maybe I will give it also translated. This is my first translation of the article, it took me nearly five hours, the article can be said to be flawed, if the translation of unreasonable please forgive me, if you are interested in improving this content can send me an e-mail. This wee hours, unexpectedly can not sleep, do not know is in other corner, also someone with me.

I hope this article will be able to learn PHP socket programming friends A little help, thank you for reading this error-ridden article

http://www.bkjia.com/PHPjc/478668.html www.bkjia.com true http://www.bkjia.com/PHPjc/478668.html techarticle The final editor Jguon charming and confusing sockets (Sockets). Sockets is a feature that is not fully utilized in PHP. Today you will see the creation of a client connection that can use the ...

  • Related Article

    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.