◆ Socket basics
PHP uses Berkley's socket library to create its connections. A socket is nothing more than 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: Protocol 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 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 two-line, reliable connection that sends fixed-length data packets for transmission. This packet 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 for use by the data link layer and does not guarantee the packet order. 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, which is a connectionless and 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 runs successfully. If it fails, it returns false.
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.
<?php
$commonProtocol = getprotobyname("tcp");//Use the public protocol name to get a protocol type
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);//Generate a socket and return an instance of the socket resource
socket_bind($socket, 'localhost', 1337);//Bind socket to local computer
socket_listen($socket);//Listen to all incoming socket connections
// More socket functionality 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() accepts a Socket connection
socket_bind() binds the socket to an IP address and port
socket_clear_error() clears the socket error or last error code
socket_close() closes a socket resource
socket_connect() starts a socket connection
socket_create_listen() opens 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() Gets the IP address of a remote similar host
socket_getsockname() gets 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() 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() gets the last error code of the current socket
socket_listen() listens to all connections from the specified socket
socket_read() reads data of specified length
socket_readv() reads data from the scatter/aggregate array
socket_recv() ends the data from the socket to the cache
socket_recvfrom() accepts data from the specified socket. If not specified, it defaults to the current socket.
socket_recvmsg() receives messages from iovec
socket_select() multiple selection
socket_send() This function sends data to the connected socket
socket_sendmsg() sends message to socket
socket_sendto() sends a message to the socket at the specified address
socket_set_block() sets the socket to block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() sets socket options
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() returns the detailed error with the specified error number
socket_write() writes data to the socket cache
socket_writev() writes data to scattered/aggregated arrays. All the above functions are related to 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 following Comment before this line:
extension=php_sockets.dll
If you can't remove the comment, use the following code to load the extension library:
<?php
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, then 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.
View phpinfo()'s 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.
<?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...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.
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:
<?php
// Set up our socket
$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 on this socket
$connection = socket_accept($socket);//socket_accept() accepts a Socket connection
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"); //socket_write() writes data to the socket cache
printf("Wrote to socketrn");
}else {
printf("No Data in the bufferrn");
}
//Get the input
while($data = socket_read($connection, 1024, PHP_NORMAL_READ))//socket_read() reads data of specified length
{
$buffer = $data;
socket_write($connection, "Information Receivedrn");
printf("Buffer: " . $buffer . "rn");
}
socket_close($connection); //socket_close() closes a socket resource
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. It then sends an accept 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.
◆ It is easy to generate a client to handle the second problem. You need to generate a php page, connect to a socket, send some data to its cache and process it. Then you have the processed data waiting, and you can send your data to the server. On another client connection, it will process that data.
The following example demonstrates the use of sockets:
<?php
// 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(“<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 DATArn”)){
echo(“<p>Write failed</p>”);
}
// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)){
echo(“<p>Data sent was: SOME DATA<br> Response was:” . $buffer . “</p>”);
}
echo(“<p>Done Reading from Socket</p>”);
?>
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 cycle, 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.