×

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

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Python 2.7 data structures

The rundown information type has a few additional techniques. Here is every one of the strategies for listing objects: list.append(x): Add a thing to the furthest limit of the rundown; comparable...

9 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Pltpcolor in Python

Python: 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 is said...

3 minutes read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

5 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.