PHP Socket Basics

Source: Internet
Author: User
Keywords PHP Socket Basics
Tags set socket socket error

Socket Basics
PHP uses the Berkley socket library to create its connection. A socket is simply 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, which are used on UNIX and Linux systems, are rarely used, and are typically used when the client and server are on the same machine
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 for use, does not guarantee packet order
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");//Use the public protocol name to obtain a protocol type
$socket = Socket_create (Af_inet, Sock_stream, $commonProtocol);//Generate a socket and return an instance of a socket resource
Socket_bind ($socket, ' localhost ', 1337);//bind socket to local computer
Socket_listen ($socket);//monitor all incoming socket connections
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
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.
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.

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:
Set up our sockets
$commonProtocol = Getprotobyname ("TCP");
$socket = Socket_create (Af_inet, Sock_stream, $commonProtocol);
Socket_bind ($socket, ' localhost ', 1337); Socket_bind () binds the socket to an IP address and port
Socket_listen ($socket);
Initialize the buffer
$buffer = "NO DATA";
while (true) {
Accept any connections coming "in" this socket
$connection = Socket_accept ($socket);//socket_accept () accepts a socket connection
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"); Socket_write () write data to the socket cache
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))//socket_read () reads the specified length of data
{
$buffer = $data;
Socket_write ($connection, "Information received\r\n");
printf ("Buffer:".) $buffer. "\ r \ n");
}
Socket_close ($connection); Socket_close () Close a socket resource
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.
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 you have a processed data in the Dayton and you are able to send your data to the server. On another client connection, it will process those data.
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.

  • 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.