Tcp Echo Server

Lesson 26: TCP echo server

Another version of this video:

Server code:

#server-receive  tcp
import socket, sys

#a socket is a pipe that connects to a port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
#Address Family_ Internet TCP
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# so we can keep using the same port
host = sys.argv[1]
port= int(sys.argv[2])
s.bind( (host, port) ) #bind to port 3335 because we are receiving
s.listen(1) #the server listens for incomming connections
try:
    while True:
            print('before accept')
            conn, addr = s.accept()  
            #blocking (waits for an incoming connection)
            print('after accept')
            #print('conn = ', conn)
            #print('addr = ', addr)                                 
            data = conn.recv(1024)                                  
            # blocking but now for data from the established connection                                                                 
            data=data.decode()                                      
            print(f'{addr[0]} says {data}')
            data= 2*data                                            
            conn.sendall(data.encode())  #or sendall                
except KeyboardInterrupt:                                           
    conn.close() #close the last blocking s.accept with Ctrl-c 

Client code:

#client-send tcp
import socket, sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #tcp sock_stream
host = sys.argv[1]
port = int(sys.argv[2])
s.connect( (host, port) )

line = input('Send :') #blocking, waits for user input
s.send(line.encode()) #not using sendall

data = s.recv(1024) #1024 number of bytes or chars blocking
print('Server replies: ',data.decode())
s.close()