Home arrow PHP arrow Page 2 - An Introduction to Sockets in PHP

The basics of low-level sockets: developing an illustrative example - PHP

Working with low-level sockets can be a painful task in PHP. Fortunately, PHP offers a nice library of socket handling functions to make your life easier. If you do a lot of network programming in PHP, you will want to check out this three-part series, which starts with the basics and takes you through more advanced approaches. This article is the first one in the series.

TABLE OF CONTENTS:
  1. An Introduction to Sockets in PHP
  2. The basics of low-level sockets: developing an illustrative example
  3. Reading and writing socket data: creating a simple web-based client application
  4. Reusing the TCP server: defining the "createSocketServer()" function and "SocketServer" class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 33
May 22, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In order to introduce the core concepts of socket programming in PHP in a friendly way, I'm going to set up a basic example, which hopefully will help to illustrate the usage of the most important socket-related PHP functions. First I'll show you how to develop a simple TCP server with sockets, and then I'll explain the meaning of each function used in the sample script.

Having said that, here's a procedural script that builds a basic TCP server. Take a look at the code listed below:

// define TCP port & local host
$port=1234;
$host='127.0.0.1';
set_time_limit(0);
// create low level socket
if(!$socket=socket_create(AF_INET,SOCK_STREAM,0)){
    trigger_error('Error creating new socket',E_USER_ERROR);
}
// tie up socket to TCP port
if(!socket_bind($socket,$host,$port)){
    trigger_error('Error binding socket to TCP
port',E_USER_ERROR);
}
// begin listening connections
if(!socket_listen($socket)){
    trigger_error('Error listening socket
connections',E_USER_ERROR);
}
// create communication socket
if(!$comSocket=socket_accept($socket)){
    trigger_error('Error creating communication
socket',E_USER_ERROR);
}
// read socket input
$socketInput=socket_read($comSocket,1024);
// convert to uppercase socket input
$socketOutput=strtoupper(trim($socketInput))."n";
// write data back to socket server
if(!socket_write($comSocket,$socketOutput,strlen($socketOutput))){
    trigger_error('Error writing socket output',E_USER_ERROR);
}
// close sockets
socket_close($comSocket);
socket_close($socket);

As you can see, the procedural script listed above demonstrates how to create a simple TCP server, where its only functionality rests in taking up a string sent by a client, then converting it to its uppercase version and finally returning it to the mentioned client. Does that sound a little bit confusing? Don't worry, it really isn't.

First, the script defines the host and port number where the TCP server will be running. In this specific case the server will be created to work as "localhost," that is its IP address will be 127.0.0.1 and it will run on the TCP port "1234."

After defining the corresponding connection parameters, the first connection socket is created by the "create_socket()" PHP built-in function, which obviously creates and returns a socket reference. Also, the first argument of this function--that is the domain parameter--specifies the protocol family to be used by the socket, in this case AF_INET, which means that it will use the IPv4 Internet-based protocols.

Additionally, the second argument indicates the type of socket to be used. In this example, I specified a value of "SOCK_STREAM," meaning that the socket will support the use of the TCP protocol. Finally, the last function parameter determines the protocol used by the socket. In this case I decided to use the reliable TCP protocol.

Of course, all the above description can be assumed in the following statement:

// create low level socket
if(!$socket=socket_create(AF_INET,SOCK_STREAM,0)){
    trigger_error('Error creating new socket',E_USER_ERROR);
}

Right, after creating the general connection socket, the script needs to bind it to the host and port defined before. To perform this operation, the "socket_bind()" function is conveniently used, as listed below:

// tie up socket to TCP port
if(!socket_bind($socket,$host,$port)){
    trigger_error('Error binding socket to TCP
port',E_USER_ERROR);
}

At this point, I created a general connection socket, which is tied to the 127.0.0.1 IP address, and will be expecting incoming connections on the TCP port 1234. Now, how do I make the socket listen to client connections? Right, you guessed it,  the "socket_listen()" function does precisely that:

// begin listening connections
if(!socket_listen($socket)){
    trigger_error('Error listening socket
connections',E_USER_ERROR);
}

Now that the general connection socket has been created and it's expecting client connections, there are a few additional things to be done yet. The first one consists of creating another communication socket, which will handle all the operations for reading and writing data. This is achieved by the "socket_read()" and "socket_write()" PHP functions respectively, and the entire reading-writing sequence is illustrated below:

// read socket input
$socketInput=socket_read($comSocket,1024);
// convert to uppercase socket input
$socketOutput=strtoupper(trim($socketInput))."n";
// write data back to socket server
if(!socket_write($comSocket,$socketOutput,strlen($socketOutput)))
{
    trigger_error('Error writing socket output',E_USER_ERROR);
}

As you can see, the above code block first reads the data sent by the client, then converts the data to uppercase and writes the string back to the client. At the end of this process, both sockets, the general and the communication one, are closed by the "socket_close()" PHP function, as shown below:

// close sockets
socket_close($comSocket);
socket_close($socket);

Wasn't that simple and fun? With a few PHP functions, I created an admittedly basic TCP server that returns the uppercase version of any string sent out by the client.

Also, before I finish writing this section, I'd like you to notice that the script uses the "set_time_limit()" function, in order to get rid of any timeouts imposed by the PHP parser. This makes a lot of sense, since the script doesn't have a clue about when an eventual client is going to inject data into the socket, so eliminating timeouts is a good approach to keep the script working properly.

Now, the sample TCP server is up and running, listening to incoming client connections. Therefore, a client application should be created, in order to determine whether the sockets just created work as expected. That's exactly what I'll do in the next section, thus click on the link below to find out how this client is created.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: