How To Build Python Chat Using UDP And TCP Protocol

Difference Between UDP and TCP Protocol

Practical implementation of Chat server using UDP protocol

Receiver Programme UDP Protocol

import socket
myp= socket.SOCK_DGRAM
afn=socket.AF_INET
s=socket.socket(afn,myp)
ip=”192.168.1.75"
port=1234
s.bind((ip,port))
while True:
x=s.recvfrom(1024)
ip = x[1][0]
data = x[0].decode()
print(ip + “ : “ + data)

Receiver Programme Explanation UDP Protocol

import socket=> importing necessary module for socket programming
myp= socket.SOCK_DGRAM=> calling protocol that is been used by udp
afn=socket.AF_INET=>calling adress family for udp
s=socket.socket(afn,myp)
ip=”your system ip"
port=any port to which you want your programme to run
s.bind((ip,port))=> binding programme to ip and port
while True:
x=s.recvfrom(1024) => receiving data from client in using whileloop
ip = x[1][0]
data = x[0].decode()
print(ip + “ : “ + data)

Sender Programme UDP Protocol

import socket
server=socket.socket( socket.AF_INET,socket.SOCK_DGRAM)
ip="192.168.1.75"=> change the ip in which recv prog running
port = 1234=>change the port in which recv prog running
server.connect((ip,port))
#print(server.recv(100))
while(True):
a=input()
b=str.encode(a)
server.send(b)

Receiver Programme TCP Protocol

import socket
import threading
server=socket.socket()=> by default uuse tcp protocol
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)=> used to reuse same port
port = 2222
ip=""=> if leave empty will pickup your system ip
server.bind((ip,port))
server.listen()
def ad(session, addr):
print(addr)
session.send(b"Server connected")
while True:
data=session.recv(100)
print(addr[0]+":"+data.decode())
while True:
session , addr = server.accept()
t = threading.Thread(target=ad, args=(session,addr))
t.start()

Sender Programme TCP Protocol

import socket
server=socket.socket()
ip="192.168.1.75"
port = 2222
server.connect((ip,port))
c=(server.recv(100))
print(c.decode())
while(True):
a=input()
b=str.encode(a)
server.send(b)

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to add WordPress support to VSCode

Adding user-facing webhook integration in your SaaS platform

Practical Binary Analysis: Ch 05 Challenge lvl5

WeChat Mini Programs the future of Mobile in China, and the World?

Softmax or LogSoftmax

A to -Z Java Script

Check string contain vowels

Some Thoughts on Modern Ecommerce Platforms

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gupta Aditya

Gupta Aditya

More from Medium

Deploying a Flask App to Heroku with MongoDB using QuotaGuard

Get started with Redis

An overview of version control and non-relational databases

NodeJS VS AngularJS: Battle of JS Platforms in 2022