×

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in python is very simple compared to any other language like C++.

Python gives access to two levels of network services which are:

  • First, it provides low-level access. In low-level access, we can access and use the basic socket support of OS with the help of python libraries.
  • Second, it provides high-level access. In high-level access, we can access the application-level networks like HTTP, FTP, etc. using python libraries.

Now before moving forward with the main topic. Let’s get familiar with some smaller concepts like Socket.

What are Sockets?

Sockets can be defined as the end-point of a communication process. In any communication process, we have end-points between two similar processes, two different processes and within a common process. These end-points are called sockets. It uses different protocols for finding the connection type of communication between client and server. It can be implemented over different channels like TCP, UDP, etc.

Python provides socket methods which help in providing virtual sockets to the communicating processes.

Syntax

s = socket.socket (socket_family, socket_type, protocol=0)

Let’s understand the vocabulary of Socket

  1. Domain: It is basically the family of protocols used for transportation.
  2. type: It represents the type of communication between two end-points.
  3. protocol: This is typically zero, but it can be used to identify the protocol used in the network.
  4. hostname: The identifier of the network. It can be any name given to the host.
  5. port: It is a specific number given to a port or a string value. It is used when the client calls for more than one port to reach the server.

Let’s understand some server methods

  • Server Socket Methods
    1. s.bind(): This method is used to bind the address to sockets.
    2. s.listen(): This method is used to set up and start a TCP listener.
    3. s.accept(): This method is used for accepting the TCP client connection.
  • Client Socket Methods
    1. s.connect(): This method is used to initiate server connections for TCP.
  • General Socket Methods
    1. s.recv():  This method is used to receive the TCP message.
    2. s.send(): This method is used to transmit the TCP message.
    3. s.recvfrom(): This method is used to receive the UDP message.
    4. s.sendto(): This method is used to transmit the UDP message.
    5. s.close(): This method is used for closing the sockets.
    6. socket.gethostname(): This method is used for returning the hostname.

A Simple Server

# Importing the socket module
import socket              


# Creating a socket object
sct = socket.socket()         
# Getting name for the local machine
host = socket.gethostname() 
# Reserving a port for the service.
port = 12445                
# Bind to the port
sct.bind((host, port))        


# waiting for the client connection.
sct.listen(7)                
while True:
   # Establishing the connection with the client.
   cs, adrs = sct.accept()     
   print 'Got connection from', adrs
   cs.send('Thank you for connecting to the server')
   cs.close()           

Explanation

In the above code, we made a socket object and reserved a port on our pc. After that, we have bounded our server to a specific port. In the above code, we have passed an empty string so that the server can listen to incoming connections from other computers as well. We have used 7 in the listen() method, which means that 7 connections are kept waiting until the server is busy, and after that, if an 8th socket tries to connect, the connection will be refused. In the end, we have used a while loop for accepting all incoming connections.

A Simple Client

This is client.py file which is used to set up the client-server.

# Importing the socket module
import socket               
# Creating a socket object
sct = socket.socket()         
# Getting a local machine name
host = socket.gethostname() 
# Reserving a port for services
port = 12445                
sct.connect((host, port))
print sct.recv(1024)
sct.close()                

Now, if we run this server.py in the background and then run client.py, we will get the connection.

# These commands will help in starting the server
$ python server.py & 


# After the server is started, we can run the client
$ python client.py

Output

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

Related Topics

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.