Echo Client & Server
MAKING OF ECHO SERVER
1.import socket and sys library as we are going to use them as main building blocks
import socket
import sys
2.Set up the socket which uses version 4 ip address and TCP protocol
door = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
3.Choose servers ip address and port through it is going to communicate and set up the socket there
server_address = ('localhost',10000)
door.bind(server_address)
4.Listen from incoming connection and max queue will be 1
door.listen(1)
5.Now the socket will perform sending and recieveing forever untill the connection is broken,so put all main code in WHILE LOOP
1.make the connection and fetch the connection and address of client
```
connection,client_address = door.accept()
```
2.Till client is sending the data recieve the data and and send it again to the client
while True:
data = connection.recv(16)
print('recieved {!r}'.format(data))
if data:
print("Sending back data to client")
connection.sendall(data)
else:
print("no data from",client_address)
break
3.When you have no recieved data then understand that client has broken the connection , server should also break the connection
finally:
connection.close()
from dataclasses import dataclass
import socket
import sys
from typing import final
# make TCP/IP door
door = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# bind the door to entrance of home (for that you need home address and home port)
server_address = ('localhost',10000)
print('starting up on {} port {}'.format(*server_address))
door.bind(server_address)
# listening for incoming guests
door.listen(1)
# now use this socket for listening to connections sent by clients
while True:
print("Waiting for connection")
connection,client_address = door.accept()
try:
print("connection from : ",client_address)
while True:
data = connection.recv(16)
print('recieved {!r}'.format(data))
if data:
print("Sending back data to client")
connection.sendall(data)
else:
print("no data from",client_address)
break
finally:
connection.close()
SAME FOR MAKING ECHO-CLIENT
# import necessary libraries
from email import message
import socket
import sys
from typing import final
# create TCP/IP socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# connect to the socket to port of server
server_address = ('locahost',10000)
print('connectign to {} port {}'.format(*server_address))
sock.connect(server_address)
# send the data and get hte response
try:
# send the data
message = b'this the message.It will be repeated'
print('sending {!r}'.format(message))
sock.sendall(message)
# get the response
amount_received = 0
amount_expected = len(message)
# take all messages
while amount_received < amount_expected:
data = sock.recv(16)
amount_received+=len(data)
print('recieved {!r}'.format(data))
finally:
print('closing socket')
sock.close()