What is socket?
Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.
Socket Module- s.socket.socket(socket_family, socket_type, protocol=0)
- socket_family-AF_UNIX or AF_INET
- socket_type-SOCK_STREAM or SOCK_DGRAM
- protocol-left out, ot defaulting to 0
Once socket object is created as mentioned above, now we can use functions below to create client server programs.
Socket methods
Sr no. | Method and Description |
---|
Server socket methods |
---|
1. |
s.bind - This method binds address hostname, port number to socket
|
---|
2. |
s.listen - This method setups and start TCP listener
|
---|
3. |
s.accept - This passively accepts client connection, waiting until connection arrives blocking
|
---|
Client socket methods |
---|
1. |
s.connect - This method actively initiates TCP server connection
|
---|
General socket methods
Sr no. | Method and Description |
---|
1. |
s.recv - This method receives TCP message
|
---|
2. |
s.send - This method transmits TCP message
|
---|
3. |
s.recvfrom - This method receives UDP message
|
---|
4. |
s.sendto - This method transmits UDP message
|
---|
5. |
s.close - This method closes socket
|
---|
6. |
s.gethostname - Returns a hostname
|
---|
Examples: sending date from server to client
client side
Output :today's Date
Python3
# importing required modules
import socket
import datetime
# initializing socket
s = socket.socket()
host = socket.gethostname()
port = 12345
# binding port and host
s.bind((host, port))
# waiting for a client to connect
s.listen(5)
while True:
# accept connection
c, addr = s.accept()
print ('got connection from addr', addr)
date = datetime.datetime.now()
d = str(date)
# sending data type should be string and encode before sending
c.send(d.encode())
c.close()
Python3
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
# connect to host
s.connect((host, port))
# recv message and decode here 1024 is buffer size.
print (s.recv(1024).decode())
s.close()
Note: Create 2 instances of python compiler to run client and server code separately do not run them on the same instance.
Output:
Server side-
Client side-
Here current date time which is fetched from server appears
UDP Sockets
UDP is USER DATAGRAM PROTOCOL, this is a lightweight protocol which has basic error checking mechanism with no acknowledgement and no sequencing but very fast due to these reasons
Examples:sending date from server to client
client side
Input : vivek
Input : 17BIT0382
Output : password match
Python3
import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
UDPServerSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
# this might be database or a file
di ={'17BIT0382':'vivek', '17BEC0647':'shikhar', '17BEC0150':'tanveer',
'17BCE2119':'sahil', '17BIT0123':'sidhant'}
while(True):
# receiving name from client
name, addr1 = UDPServerSocket.recvfrom(bufferSize)
# receiving pwd from client
pwd, addr1 = UDPServerSocket.recvfrom(bufferSize)
name = name.decode()
pwd = pwd.decode()
msg =''
if name not in di:
msg ='name does not exists'
flag = 0
for i in di:
if i == name:
if di[i]== pwd:
msg ="pwd match"
flag = 1
else:
msg ="pwd wrong"
bytesToSend = str.encode(msg)
# sending encoded status of name and pwd
UDPServerSocket.sendto(bytesToSend, addr1)
Python3
import socket
# user input
name = input('enter your username : ')
bytesToSend1 = str.encode(name)
password = input('enter your password : ')
bytesToSend2 = str.encode(password)
serverAddrPort = ("127.0.0.1", 20001)
bufferSize = 1024
# connecting to hosts
UDPClientSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
# sending username by encoding it
UDPClientSocket.sendto(bytesToSend1, serverAddrPort)
# sending password by encoding it
UDPClientSocket.sendto(bytesToSend2, serverAddrPort)
# receiving status from server
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0].decode())
print(msg)
For simplicity in the code, I have chosen a dictionary you can use a database, file or CSV file, etc. for various other purposes.
Output:
Similar Reads
Python Modules Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python Arrays Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
asyncio in Python Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
4 min read
Calendar in Python Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
2 min read
Python Collections Module The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
13 min read
Working with csv files in Python Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
10 min read
Python datetime module In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
14 min read
Functools module in Python The functools module offers a collection of tools that simplify working with functions and callable objects. It includes utilities to modify, extend, or optimize functions without rewriting their core logic, helping you write cleaner and more efficient code.Let's discuss them in detail.1. Partial cl
5 min read
hashlib module in Python A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
5 min read
Heap queue or heapq in Python A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
7 min read