Socket Basics

PHP uses the Berkley sockets library to make its connections. You can think of a socket as nothing more than a data structure. You use this socket data structure to start a conversation between a client and a server. The server is always listening to open a new conversation. When a client wants to talk to the server, it opens a conversation through a specific port on which the server is listening. When the server receives the client’s request it completes the connection, thus completing the cycle. Now the client can send information to the server and the server can send information to the client.

To create a socket you will need three variables: a protocol, a socket type, and a common protocol type. There are three protocols that you can choose from when creating a socket. Take a look at Table 10.1 for the names of the protocols and a description of what each protocol does.

When you create your own server you will use the AF_INET protocol. There are five socket types to choose from in the Berkley socket library. Please refer to Table 10.2 for the constant and a description of the socket type.

The final element to creating a socket is to define the type of common protocol that the connection should use. Table 10.3 lists the name and the description of the three common protocol types.

Table 10.1. Protocols
Name/Constant Description
AF_INET The most common of the protocols that are used when creating sockets. AF_INET uses TCP or UDP and an IPv4 address.
AF_INET6 Similar to the AF_INET but uses an IPv6 address instead of an IPv4 address.
AF_UNIX A local communication protocol. This is specific to UNIX and Linux, and it uses the file system to define its socket connections. This protocol is rarely used. When it is used, the client and server are usually on the same machine.

Table 10.2. Socket Types
Name/Constant Description
SOCK_STREAM This socket type provides sequenced, reliable, full-duplex connections based on byte streams. This is the most commonly used socket type. This is also the socket type that the TCP common protocol uses.
SOCK_DGRAM This socket type provides connectionless, fixed-length transmissions called datagrams. This socket type is fairly unreliable. UDP uses this socket type for its connections.
SOCK_SEQPACKET This socket type provides a two-way, reliable connection for sending fixed-length transmissions. The receiver is required to read the entire packet for every read call made when using this socket type.
SOCK_RAW This socket type provides raw network protocol access. The ICMP common protocol (ping, traceroute, and so on) uses this socket type.
SOCK_RDM This socket type is rarely used and is not implemented on most operating systems. This provides a datagram layer that does not guarantee the ordering of your packets.

Table 10.3. Common Protocols
Name/Constant Description
ICMP The Internet Control Message Protocol. It is used mostly by gateways and hosts to report errors in communication.
UDP The User Datagram Protocol. As mentioned previously, this is a connectionless, unreliable way to transmit data.
TCP The Transmission Control Protocol. This is the most common and most reliable of the common protocols. TCP guarantees that its packets will arrive to the recipient. If there were errors during transmission, TCP re-broadcasts the packets to make sure they show up error free.

Now that you know the three elements for creating a socket, take a look at the socket_create() function that PHP uses to create a socket. The socket_create() function takes three parameters: a protocol, a socket type, and a common protocol. The socket_create() function returns a resource to the socket if it was created successfully, or it returns false if the socket was not created successfully.

resource socket_create(int protocol, int socketType, int commonProtocol);

Now that you can create a socket, how can you use it? PHP provides several functions to handle sockets. You can bind sockets to an IP, listen for communication on a socket, accept a socket; the list just goes on and on. Start by taking a look at an example to see what functions you will need to create, accept, and listen 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 example above is a start to creating your own server. The first line of the example,

$commonProtocol = getprotobyname(“tcp”);

gets the protocol type that you are going to use by name. In this case you want to use the TCP common protocol. If you wanted to use UDP or ICMP you would pass “udp” or “icmp” as the parameter to the getprotobyname() function. An alternative to using the getprotobyname() function is specifying either SOL_TCP or SOL_UDP as the final argument to the socket_create() function.

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

The second line of the example creates the socket and returns the instance of the socket resource. After you have the instance of the socket resource, you need to bind the socket to a certain port and IP address.

socket_bind($socket, ‘localhost’, 1337);

In this case you are binding the socket to your local computer (127.0.0.1) and you are binding the socket to port 1337. After everything is created and bound you must listen for a connection to come in to the socket.

socket_listen($socket);

These are just four of the functions used in the wonderful world of sockets. Take a look at Table 10.4 to see all the functions that sockets use.

Table 10.4. Socket Functions
Function Name Returns Description
socket_accept(resource socket) resource After you have created a socket, bound it, and started listening on that socket, this function will accept incoming connections.
socket_bind(resource socket, string address, int port) bool This binds the socket resource to the address and port specified. socket_bind() will return TRUE if it succeeds and FALSE if it fails.
socket_clear_error([resource socket]) void This will clear the errors on the specified socket. If a socket is not specified then it clears the global last socket error.
socket_close(resource socket) void Closes the created socket.
socket_connect(resource socket, string address, [int port]) bool Attempts to connect to the socket resource. Returns TRUE if connection succeeded and FALSE if the connection failed.
socket_create_listen(int port, [int backlog]) resource Creates a new AF_INET socket that listens on the specified port. Backlog defines the length of the queue of pending connections.
socket_create_pair(int protocol, int socketType, int commonProtocol, array &fd) bool This creates a pair of sockets that are stored in the array fd. There is no way to distinguish between the two sockets.
socket_create(int protocol, int socketType, int commonProtocol)resource Creates a new socket.
socket_get_option(resource socket, int level, int optname) mixed This function retrieves the options for a socket.
socket_getpeername(resource socket, string &address, [int &port]) bool This function returns the remote IP address of the connecting peer computer.
socket_getsockname(resource socket, string &address, [int &port]) bool This function returns the local IP address of the socket.
socket_iovec_add(resource iovec, int iov_len) bool This function adds a new vector to the scatter/gather array.
socket_iovec_alloc(int num_vectors) resource This function builds a iovec structure for use with sendmsg, recvmsg, writev, and readv.
socket_iovec_delete(resource iovec, int iov_pos) bool Deletes the allocated iovec.
socket_iovec_fetch(resource iovec, int iovec_pos) string Returns the data held in the iovec_pos in the specified resource.
socket_iovec_free(resource iovec) bool Frees the iovec resource.
socket_iovec_set(resource iovec, int iovec_position, string new_val) bool Sets the data at iovec_position to the new value.
socket_last_error([resource socket]) int Retrieves the last error code that occurred on any socket. If a socket is specified, it returns the last error that occurred for that socket.
socket_listen(resource socket, [int backlog]) bool Listens for a connection to the specified socket. Backlog defines the length of the queue for pending connections.
socket_read(resource socket, int length, [int type]) string This reads length bytes from the specified socket. Type can be PHP_BINARY_READ or PHP_NORMAL_READ. If PHP_BINARY_READ is used, the string is a binary string; otherwise the string is a normal string with normal escape characters.
socket_readv(resource socket, resource iovec) bool Reads from the fd array using the scatter/gather array.
socket_recv(resource socket, string &buffer, int length, int flags) int Receives data into buffer on a connected socket.
socket_recvfrom(resource socket, string &buffer, int length, int flags, string &name, [int &port]) int Receives data from a socket whether or not the socket is currently connected.
socket_recvmsg(resource socket, resource iovec, array &control, int &controlLength, int &flags, string & address. [int &port])bool This function is used to receive messages on a socket that uses iovectors.
socket_select(array &read, array &write, array & except, int tv_sec, [int tv_usec]) int This function accepts an array of sockets to watch. The sockets that are passed in the read array are watched for characters that become available for reading. The write array is watched for blocks that are written to. The except arrays are watched for exceptions.
socket_send(resource socket, string buffer, int length, int flags) int This function sends data to a connected socket.
socket_sendmsg(resource socket, resource iovec, int flags, string address, [int port])bool Sends a message to a socket.
socket_sendto(resource socket, string buffer, int length, int flags, string address, [int port]) int This function sends length of the buffer through the socket to the specified address.
socket_set_block(resource socket) bool Sets the blocking mode on a socket.
socket_set_nonblock(resource socket) bool Sets non-blocking mode on a socket.
socket_set_option(resource socket, int level, int optname, mixed optval)bool Sets the socket options for a socket.
socket_shutdown(resource socket, [int how]) bool This function allows you to shut down reading, writing, or both for the specified socket. how can be 0, 1, or 2.
socket_strerror(int errorNumber) string Returns a description of the specified error number.
socket_write(resource socket, string buffer, [int length])int Writes the buffer to the socket.
socket_writev(resource socket, resource iovec) bool Writes to the fd array using the scatter/gather array.
* At the time of this writing, www.php.net did not have definitions for every socket function.

Those are all the functions that PHP offers for use with sockets. You should already have sockets enabled, but if you don’t, then edit the php.ini file and uncomment the line that says:

extension=php_sockets.dll

If you don’t uncomment this line you could load the extension dynamically using the fol-lowing code:

<?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 sockets are enabled you can always use the phpinfo() function to determine if sockets are enabled. There should be a section that looks like Figure 10.1.

Figure 10.1. Viewing the phpinfo() for sockets.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset