Practical 1
Aim: Write a program to implement Concurrent Echo Client Server
Application.
Server Code (server.py)
import socket
import threading
class EchoServer :
def __init__ ( self , host = ’ 127.0.0.1 ’ , port =65432) :
self . host = host
self . port = port
self . server = None
def handle_client ( self , conn , addr ) :
print ( f " Connected ␣ by ␣ { addr } " )
with conn :
while True :
data = conn . recv (1024)
if not data :
break
conn . sendall ( data )
print ( f " Connection ␣ closed ␣ { addr } " )
def start ( self ) :
with socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) as
s:
s . bind (( self . host , self . port ) )
s . listen ()
self . server = s
print ( f " Server ␣ started ␣ at ␣ { self . host }:{ self . port } " )
while True :
conn , addr = s . accept ()
client_thread = threading . Thread ( target = self .
handle_client , args =( conn , addr ) )
client_thread . start ()
if __name__ == " __main__ " :
server = EchoServer ()
server . start ()
Client Code (client.py)
1
import socket
class EchoClient :
def __init__ ( self , host = ’ 127.0.0.1 ’ , port =65432) :
self . host = host
self . port = port
def start ( self ) :
with socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) as
s:
s . connect (( self . host , self . port ) )
print ( f " Connected ␣ to ␣ server ␣ { self . host }:{ self . port } " )
while True :
message = input ( " Enter ␣ message ␣ to ␣ send ␣ ( or ␣ ’ exit ’
␣ to ␣ quit ) : ␣ " )
if message . lower () == ’ exit ’:
break
s . sendall ( message . encode () )
data = s . recv (1024)
print ( f " Echoed ␣ from ␣ server : ␣ { data . decode () } " )
if __name__ == " __main__ " :
client = EchoClient ()
client . start ()
Output Screenshots
Server Output
Client Output