Socket Programming with Python

Tirumalaparise
2 min readJan 17, 2021

🔅 Create your own Chat Servers, and establish a network to transfer data using Socket Programing by creating both Server and Clinet machine as Sender and Receiver both. Do this program using UDP data transfer protocol.

Socket Programming:

A Socket is a combination of IP address and port number.It helps to uniquely identify a process (application)running on the system.To communicate with another system ,the connecting system(client) should know the IP of the system (server) and port number on which it is running.

Using UDP to establish communication between server and clinet:

First to create a socket import the socket module and then create a socket from submodule socket specifying to use UDP protocol as

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #creating UDP socket
s.bind((“192.168.43.22”,4445))#binding the socket

Through the created socket ,data can be sent and received as

s.sendto(msg.encode(),((<server IP>,<server appliction port>)))
reply=s.recvfrom(1024) #receives from the socket that is sent by anyone

To make it like a chat program use a while loop that prompts the user to message to server infinetly until some condition is met(like pressing ENTER)

When client presses ENTER the client process ends (socket is closed) using socket.close()

while(True):
msg=input(‘Enter msg to send:’ )
if(msg==’’’):
s.close()
break
s.sendto(msg.encode(),((sip,sport)))
reply=s.recvfrom(1024)
print(reply[0].decode())

Chatting program using UDP

Here the client and server Sockets IPs and port numbers are either taken dynamically or hardcoded.

--

--