“Code less, achieve more” is the prime philosophy behind the development of all the Very High Level Languages (or VHLL in short). But a fewer number of lines should not mean reduced flexibility in terms of choosing an approach for solving a problem. Though many of the VHLL, or scripting languages as they are popularly known, do not keep flexibility in mind the flexibility, there are a few that have the logic of flexibility and choice as their core. Python is one of them. This fact is evident if one tries to do network programming in Python. There are plenty of choices for the programmer. These range from low-level sockets or raw-sockets to a completely extensible and functional web server. In this tutorial I will be discussing how to use raw sockets to create network oriented applications in Python. In the early part, I will cover the basics of the socket module, and a simple echo server will be coded. Later on, the echo server will be enhanced by making it capable of serving multiple clients using the concepts introduced in the first section. Sockets and Ports -- Doing it the Python way Sockets and ports form the core of any network oriented application. According to the formal definition a socket is “An endpoint of communication to which a name may be bound.” The concept (as well as implementation) comes from the BSD community. The 4.3BSD implementation defines three domains for the sockets: Internet Domain NS Domain Of these only the first two are commonly used. Python supports all of these. My discussion will be limited to the Internet domain. The following are the steps necessary for creating an application that uses TCP/IP sockets: 1. Creating a socket But before creating a socket, libraries have to be imported. The socket module contains all that is needed to work with sockets. The imports can be done in two ways: import socket or from socket import *. If the first form is used, then to access the methods of socket module, socket.methodname() would have to be used. If the latter form is used, then the methods could be called without the fully qualified name. I will be using the second form for clarity of the code and ease. Now let's see the various provisions within the socket module for the programmers.
blog comments powered by Disqus |