Networking in Python, Sockets

by
Share this Article: Facebook0Google+0Twitter5LinkedIn0Reddit0StumbleUpon0

The key to networking in Python is the socket module, which provides a library for making network connections using Python.

The socket module is used for low level networking and it provides the standard BSD Sockets API. Unix programmers are very familiar with this networking service. If you want to build server sockets and clients, this the module that everything for you. There are a number of channels in which a socket may be implemented, such as TCP, UDP, Unix sockets and so on. Any communication goes through sockets, once you create a socket and are successfully connected you can read and write information from it. When you connect to facebook.com, your computer creates a client socket which will fetch the Facebook page. In simple words, the client socket retrieves information from the Facebook servers. To create a socket you must first import the socket module and use the socket.socket() function to create it. The syntax for this is shown below:

>>>import socket

>>>sock=socket.socket(socket_family,socket_type,protocol=0)

The socket family is either AF_UNIX or AF_INET. The socket type is either SOCK_STREAM or SOCK_DGRAM and the protocol default is set to zero. Once you have created the socket object you can use it to create a client socket or server socket by using specific functions for each one.

Server Socket Methods

Method Description:

s.bind() This method binds address (hostname, port number pair) to socket.
s.listen() This method sets up and start TCP listener.
s.accept() This passively accept TCP client connection, waiting until connection arrives (blocking).

Client Socket Methods

Method Description:

s.connect() This method actively initiates TCP server connection.

After you have learned server socker methods and client socket methods you can create a simple client which connect to a simple server. You can use your imagination to create a simple chat. You can read my previous articles on how to create a server and client in Python programming language.

For questions please refer to our Q/A forum at : http://ask.unixmen.com/

Share this Article: Facebook0Google+0Twitter5LinkedIn0Reddit0StumbleUpon0