Python Networking

Python allows you to two levels of access to the network services:

  • at low level - in the low level, you can only access to the basic socket support in the underlying OS, allows you to implement the clients and servers for both connection-oriented and connectionless protocols
  • at high level - python have libraries, provides higher-level access to the particular application-level network protocols, such as HTTP, FTP, etc.

What is Socket ?

Socket is the endpoint of a bi-directional communications channel. Sockets can communicate within a process, between the processes on the same machine, or between the processes on the different continents.

A Simple Server

To write the internet server, we will use the function socket() available in the socket module to create the socket object. A socket object is then used to call the other functions to setup the socket server. Now call the function named bind(hostname, port) to specify a port for your service on the given host. Next, call the method named accept() of the returned object. This method waits until a client connects to the port you have specified, and then returns a connection object that represents the connection to that client. Here is an example demonstrating all this. This is server.py file:

# Python Networking - Example Program

import socket               # this import the socket module

s = socket.socket()         # this creates a socket object
host = socket.gethostname() # this will get the local machine name
port = 12345                # this reserves a port for your service.
s.bind((host, port))        # this bind to the port

s.listen(5)                 # this wait for the client connection.
while True:
   c, addr = s.accept()     # this establish connection with the client.
   print("Got connection from", addr)
   c.send("Thank you for connecting")
   c.close()                # this will lose the connection

A Simple Client

Here is a simple client program, which opens a connection to a given port 12345 and given host. This is client.py file.

# Python Networking - Example Program

import socket 

s = socket.socket()
host = socket.gethostname()
port = 12345 

s.connect((host, port))
print(s.recv(1024))

s.close()

Now run the server.py file in the background and then run the client.py to see the result:

$ python server.py &

$ python client.py

It will produce following result:

Got connection from ('127.0.0.1', 48437)
Thank you for connecting

Python Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋