Wednesday, February 22, 2012

Socket programming in Python

Python and why it might be worth taking a look at
Python is an interpreted language, like perl or php. Code is written and saved in a file, made executable like a shell script (or not), then run by executing the file or invoking the interpreter with the file name as an argument. It runs on just about every OS in use and is extremely portable. The biggest advantage, however, is that the syntax is simple and results in code that is almost self-commenting. As for drawbacks, it will definitely run slower than C or C++, so if speed is absolutely critical then it’s probably not for your project. However, I have it on good authority that some big companies tend to embed the python interpreter in their C software in case they need to quickly extend their project. Check out this article for the perspective of someone versed in many languages, as opposed to a lazy sys admin who use bash and python and silently ignores his C++ books.
On to sockets
Python supports two types of sockets, UNIX (AF_UNIX) and Internet (AF_INET), and two types of protocols, TCP (SOCK_STREAM) and UDP (SOCK_DGRAM). Unix sockets are used for interprocess communication and the rest you’ve probably worked out already. The main module used in socket programming is socket and the function within this module used to create sockets is called, you guessed it, socket(). The socket function has the syntax:
socket(socket_family, socket_type, protocol=0)
So creating a TCP/IP socket might look like this:
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
And a UDP socket like this:
socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


Links
http://python.org/ Python homepage

No comments:

Post a Comment