×

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

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

AES CTR Python

Python Programming Language  Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.