| free hosting image hosting hosting reseller online album e-shop famous people | ||
![]() ![]() |
||

An introduction to socket programming
Intended Audience
Python programmers who would like to learn sockets and how to use them.
Introduction
Just like a musician needs to know notes and scales, so a programmer needs to know certain things and have available knowledge in his/her possession that allows him/her to do whatever he/she wants to. Sockets are one of those need to know programming skills.
Some terminology
Before I begin, I feel that it's neccesary for you to know some basic terminology. You may skip this section if your familiar with theses terms
Protocol - Communication language used in a network
Node - Anything that is connected to a network
Server - A special computer/program that provides a service to clients(computers connecting to it)
Client - A computer/program that is connected to a server
Peer 2 Peer - 2 connected Nodes that act both as client and server
IP Address - A number which uniquely identifies each node on an IP network. e.g. 192.168.0.1
Remote host - The computer on the other side of the network
Local host - Your own computerThese defintions are not set in stone, and are only guidance defintions. If I were to give you technical gibberish now youd be lost right?
A little bit of history
One day, long long long ago there were computer networks. All these networks were created by hardware vendors, governments and companies alike. The problem with this was that these networks were incompatible with each other. Things that we today take for granted, like sending e-mail to each other or browsing the web, was once impossible. Each network had their own protocols and standards. Interoperability was becoming a huge problem. Enter the American department of defence. In the 1960's they formed ARPA?[1], who were a collection of universities and government organisations. ARPA started creating TCP/IP, which is now the defacto standard network protocol suite. The universities whom helped to create the protocols also started using them to share data, and so the internet was born.
How does it work?
I could go on for hours about this one topic, if you feel you need to know alot more, do some research using google, or read a book. I will try though, to explain it in the shortest way possible. You can read my mini e-book on TCP/IP if you'd like some deeper knowledge on the protocols(note that I wrote this thing quite a few years ago) .
Internet Protocol
IP is the lower level protocol that is used to transfer data over a network. IP identifies each host with an IP address, which is currently four octal numbers devided by periods.e.g. 196.12.13.205. Because an IP address consists of octal numbers, a single number in an IP address can only range from 0-255. That gives you 256 possible values for each octet.
IP sends data in small little units called packets, each packet contains information, such as who its from and where its going, and then the data of course. The packets are sent through the network, and routers determine where it goes next, until it reaches its destination or gets dropped.
IP doesn't care whether data is delivered reliably or not, it just throws the data at the network, and doesn't check whether it arrives. It was decided that these things should be handled by another higher level protocol
Transmission Control Protocol
TCP uses advanced methods to make sure data reaches it's destination reliable and whole. TCP is connection oriented, which means the client(the computer requesting the connection) and the server(the computer recieving the connection request) agree to exchange data, and when they are finished this agreement is terminated.
TCP/IP is everywhere, when you check e-mail your mail program connects with TCP/IP to your mailserver and then exchanges data, the same goes for the www.
Lets begin
Without further adue, lets begin, there are several steps we need to take to make this thing happen:
1. Create a socket
2. Connect it to a server
3. Send some data
4. Recieve some data
5. Close the socket1. Creating a socket
First of all we need to import the socket module
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)So whats all this then? Well, AF_INET is a constant that tells python we are creating a Internet protocol socket, and the SOCK_STREAM means we are using TCP as the higher level protocol
2. Connecting To a remote host
host = "www.google.com"
port = 80
try:
s.connect((host, port))
except socket.error, (errno, strerror):
print errno + " " + strerrorFirst of all we tell python who we want to connect to, and which port. port 80 is the standard HTTP port. I am using exception handling here because alot of things can go wrong, like if I typed gogle.com it might have been invalid. If all goes well, we are connected and ready to send and recieve data.
3. Sending Data
We will be asking google.com for their mainpage. In order to do this we have to speak some HTTP
s.send("GET /\n\n")
The double newline is a part of The HTTP protocol, so don't worry about it. Now the request has been send for the index page. The webserver will reply!
4. Recieving data
while True:
try:
data = s.recv(1024)
print data
except socket.error, (errno, strerror):
print errno + " " + strerror
breakYes, that is an infinite loop, the loop is waiting for data to come into the socket, and then it prints the data to the screen, The recv function reads data from the socket. The 1024 is just the buffer size in bytes that are read at any one time. When an error occurs we break out of the loop.
4. Closing the Socket
while True:
try:
data = s.recv(1024)
print data
s.close # Lets close the socket!
except socket.error, (errno, strerror):
print errno + " " + strerror
breakNow we are just cleaning it up a bit, and closing the connection after we have read data. So modify your code to look like the code above. We have now succesfully created a socket, sent data through it, and closed the connection.
Threading Sockets
The while loop above will lock the program up until data is read from the socket, which is bad. It's a good idea to put this loop into a seperate thread of execution.
Server sockets
At the moment Im gonna leave you with client sockets. Later I will add server sockets. Then we will have to make threads, because we want to listen for connections, and at the same time send and recieve data from the client. Server sockets introduce slightly more complexities, but are still very simple, in Python anyway
The End
You can check out my TCP/IP modules in the code section of this website. They are relatively easy to use and do alot of this stuff for you.
Author: Tjaart Blignaut
[1] My facts might be a bit rusty on this one
EOF