Hi,

Today I was writing SOCKET PROGRAMMING using PYTHON. I was seeing a  socket programme of Server Client echo programme in C. It was large in  size. Then I thought I will be writing using PYTHON, My aim was to make  it small and efficient. In almost every LINUX Distro comes with PYTHON  environment built-in it. Finally after a long time I come with a  solution like as follows.

UDP ECHO SERVER-CLIENT PROGRAMME

Server side Programme

#!/usr/bin/env python
#file name: udp_echo_server.py
#Author Bamacharan Kundu
from socket import *
host = ”
port = 2156
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
while 1:
data, addr = UDPSock.recvfrom(buf)
if not data:
break
else:
print “\nReceived message”, data, “…”
data = raw_input(“Enter the data to be sent >>”)
UDPSock.sendto(data, addr)
print “Sending reply”, data, “….”
UDPSock.close()

Client side Programme

#!/usr/bin/env python
#file name: udp_echo_client.py
#Author  : Bamacharan Kundu
from socket import *
import sys
host = “localhost”
port = 2156
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
data = raw_input(‘Enter message to send to server…>’)
if not data:
sys.exit(1)
else:
if (UDPSock.sendto(data,addr)):
print “Sending message “, data,”….”
data, addr = UDPSock.recvfrom(buf)
print “\nReceived message”, data, “…”
UDPSock.close()

SERVER-CLIENT CHAT PROGRAMME USING TCP

Server side code:

#!/usr/bin/env python
#file name: tcp_chat_server
from socket import *
import sys
host = ”
port = 50007
s = socket(AF_INET, SOCK_STREAM)
addr = (host, port)
s.bind(addr)
s.listen(2)
while 1:
conn, addr_c = s.accept()
print “Connected by”, addr_c
while 1:
data = conn.recv(1024)
if not data:
conn.close()
continue
print “data received is “, data
data = raw_input(“Enter data to send …”)
conn.send(data)

Client Side Programme

#!/usr/bin/env python
#tcp_chat_client
from socket import *
import sys
host = ‘localhost’
port = 50007
s = socket(AF_INET, SOCK_STREAM)
addr = (host, port)
s.connect(addr)
while 1:
data = raw_input(‘Enter message to send >>”)
if not data: break
else:
s.send(data)
data = s.recv(1024)
print “Received”, data
s.close()

While writing programs I got help form The Official docs of PYTHON.

Try it have a fun.