Introduction to Socket Programming with PHPAre you one of those sorry souls who has desperately tried to learn network programming in C, but never had the stamina to tame the wild beast? I was for a long time until I finally decided that I had to learn it -- not only for my own satisfaction, but because I bumped into a problem that required some network programming. After a few sweaty nights, I became completely overwhelmed. Then I realized that my favorite programming language of all time, PHP, included a basic socket implementation. Hallelujah! I was saved!
Understanding socketsWhat PHP unfortunately won't do for you is give you a basic understanding of what sockets really are, and how you can use them to create communication between two computers. So we'll have to go through that part ourselves. It's really not that hard, and hopefully this article will make it even easier.
You know what a network is, right? Know what a socket is? Not really? Sockets are just an abstraction of a low-level feature of the operating system. However, we don't need to go that deep to use sockets in our programs. We just need to get a basic understanding of how the socket philosophy works.
To explain this, I'll compare the process to a videogame, a game that resembles the real world quite closely, except that in the game all computer networks are organized by small men. You can control these small men to do exactly what you want, but there is a drawback. These men don't have any intelligence of their own -- they will do exactly as they are told, no matter how wrong that happens to be.
Figure 1: Controlling a network with small men.
There's actually a really simple solution to this problem: Just ask another man to lead whatever came in through the hatch to its destination inside the machine. In doing this, you are letting the first man continue to concentrate on his hatch job.
But we're not done yet: You also have to make one of the men in Computer II go to the hatch on his end to make sure the hatch is opened when something wants to get out. I'll play the first game, so you can see how it works. I start out by pushing a few buttons, and move the joystick around and voilà -- we have Figure 2.
Figure 2: Here everything is in place.
After some more pushing, slamming, and banging around on the controls, I've told Computer II that I need to get some data, and have directed the man in Computer II open the hatch so the data can get out. In Figure 3, the data is on its way.
Figure 3: Data on its way!
Figure 4: Data has arrived!