• home
  • forum
  • my
  • kt
  • download
  • Introduction to PHP Sockets

    Author: 2007-08-13 10:11:16 From:

    Today we'll be taking a look at one of PHP's more underused features: Sockets. Sockets can be used to open connections to other peoples computers, or to accept incoming connections on your own computer. In this tutorial, I will try my best to explain the basics of socket programming, in an easy to understand format.


    NOTE: There are two ways to open a socket, using the socket_ functions, and using the fsockopen() function. With an fsock, you cannot listen for connections, you can only connect to other computers. In this tutorial, I will be discussing the socket_ functions.

    The first step to using a socket, is to actually create it. This can be accomplished with the socket_create() function. The syntax of this function is as follows:

    resource socket_create ( int domain, int type, int protocol)

    And an Example of this in use is:

    PHP Example: (!)

    $socket 
    socket_create(AF_INET,SOCK_STREAM,SOL_TCP);


    This may look a bit confusing to you at first, but worry not, because I will soon explain everything to you. The First parameter of the socket_create() function, is the domain. There are typically two domains:

    (Taken Directly from the PHP Manual)
    AF_INET - IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
    AF_UNIX - Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

    You will usually be working with the AF_INET domain, because this is the domain that is used for anything internet-based. The second, or 'type' parameter, is the type of socket this will be. SOCK_STREAM is a full duplex, meaning you can read from, and write to the socket. This will probably always be your type. The last parameter is the protocol. PHP has 3 major protocols, icmp, udp, and tcp. SOL_TCP is PHP's constant for a TCP protocol.


    NOTE: You can also use getprotobyname("TCP"), or simply "0" instead of SOL_TCP,whatever rocks your boat.

    So you've created your socket, great! But it isn't of much use just lying there, right? So lets PUT it to use! You can connect to other computers using a socket, with the socket_connect() function. The syntax for socket_connect() is:

    bool socket_connect ( resource socket, string address [, int port])

    The socket that we made earlier is what we call a resource. We assigned it to the variable $socket, and will now use $socket wherever we need to specify the socket we're talking about. The address parameter is self explanitory. Now that we have both the socket_create, and socket_connect functions down, lets try something useful! Lets connect to an IRC Server, on the port 6667.

    PHP Example: (!)

    $socket 
    socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // create the socket
    $connection socket_connect($socket,'irc.freenode.net',6667); 
    //connect to irc.freenode.net


    That was very simple, now wasn't it?


    NOTE: If you don't know what IRC is, it stands for Internet Relay Chat and is a popular, and fast growing way to chat online, and download things. You can connect to IRC using mIRC, if you're on windows. (www.mirc.com). or BitchX or X-Chat, if you're on Linux.



    Reading from a socket

    Reading from a socket is very simple, and can all be done without a sweat, using the socket_read() function.

    string socket_read ( resource socket, int length [, int type])

    Lets add this function to our IRC Connection, so that we can see what the IRC server is telling us.

    PHP Example: (!)

    $socket 
    socket_create(AF_INET,SOCK_STREAM,SOL_TCP); //make the socket
    $connection socket_connect($socket,'irc.freenode.net',6667); 
    //connect to the IRC server
    while($data socket_read($socket,2046,PHP_NORMAL_READ)) 
    //listen for any data, and echo that data out
    {
    echo 
    $data
    ;
    }


    With me so far? Good.


    NOTE: PHP_NORMAL_READ is a type of reading that will stop whenever the line terminates with a \r\n.


    Writing to a socket

    Writing to a socket is as easy as the socket_write() function. Note its syntax: int socket_write ( resource socket, string buffer [, int length]) The Resource socket would be our $socket variable, the buffer is simply what you want to write to it. Lets add this feature to our IRC Connection, and Join a channel! Hm..how about #test? :)

    PHP Example: (!)

    $socket 
    socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // Create the Socket
    $connection socket_connect($socket,'irc.freenode.net',6667); 
    // Connect to freenode
    socket_write($socket,"USER RHAP RHAP RHAP :RHAP\r\n"); 
    // Send the Username to freenode
    socket_write($socket,"NICK MyFirstSocket \r\n"); 
    // Change our nickname
    socket_write($socket,"JOIN #TEST \r\n"); 
    // Join the channel PHPFREAKS!!!
    while($data socket_read($socket,2046)) 
    // read whatever IRC is telling us
    {
    echo 
    $data
    ;
    }


    In this socket, I wrote "USER", "NICK", and "JOIN". These are IRC Commands that will allow me to define a username, change the nickname, and join the channel #test. Also note \r\n is used to end a line. Congratulations, You've written your first IRC Bot. But we're barely halfway!

    So far you've connected to, written and read from a socket. In this section of the tutorial, I will teach you how to Create a socket for users to connect to, and also how to accept users once they try to connect. Lets start by recreating our socket, nothing is different.

    PHP Example: (!)

    $socket 
    socket_create(AF_INET,SOCK_STREAM,SOL_TCP);


    Now instead of connecting to a socket, we'll bind this socket to our own machine. We do this using the socket_bind() function.

    bool socket_bind ( resource socket, string address [, int port])

    We can use it like this:

    PHP Example: (!)

    socket_bind
    ($socket,'localhost',1337);


    This will bind our socket to localhost, at the port 1337 (:D). Localhost in this example is equal to 127.0.0.1, the address the computer uses to refer to itself. A normal bind would be to whatever your IP Address is. For simplicity's sake, we'll assume your IP address was 123.123.123.123 from here on out. We would then use socket_bind() as follows:

    PHP Example: (!)

    socket_bind
    ($socket,'123.123.123.123',1337);


    Now that we've bound a socket to our computer, let's listen for incoming connections. Note that the way I'm using here can only accept one connection at a time. We will listen for connections using socket_listen() and accept any connections with socket_accept().

    PHP Example: (!)

    $socket 
    socket_create(AF_INETSOCK_STREAMSOL_TCP); // Create our socket.
    socket_bind($socket,'123.123.123.123',1337); 
    //bind the socket to our IP address, on port 1337.
    socket_listen($socket); 
    // listen for any incoming connections
    while($connection socket_accept($socket)) 
    // accept any incoming connection and write to the socket.
    {
    socket_write($connection,'You\'ve successfully connected to my computer!\r\n'
    );
    }


    In this example, Your socket will listen for any connections. Once a connection attempt is detected, it will accept the connection, and write "You've successfully connected to my computer!" to the socket. You can try this example yourself, by telnetting to your IP address, on the port 1337. The functions socket_read and socket_write, and most other socket_ functions will work the same if you're connecting, or listening.

    I hope this tutorial helped you understand what exactly a socket is, and how to use them to connect to an address, and to listen for connections. Please note that this tutorial was VERY basic, hence "Introduction", and was simply made to give you an idea of what sockets are and how to use them. With this feature, you can do many things including Bots and MUDs. My Examples in this tutorial were very easy, so that they were understandable. Toy around with sockets, and see what you can do with them, If you come up with something original, feel free to E-Mail me and tell me all about it.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (6)
      Site Navigation (7)
      User Authentication (10)
      WAP and WML (7)
      Web Fetching (0)
      Web Traffic Analysis (11)
      XML and PHP (0)

    New

    Hot