There are 3 basic elements of client server system ->
- Client -> Sends the request to server for resources
- Server -> Sends the resources to client on the request
- Socket -> Gateway for sending and recieving the request
To program this we have 4 basic steps ->
- Server starts listening
- Client sends the request to Server and connects to it
- Server serves the request
- When client sends "Over & Out" this system terminates from both sides
Server Side Code
1.setup the host
host = socket.gethostname()
2.setup the port
port = 3000
- setup socket_instance & bind host and port
server_socket = socket.socket() server_socket.bind((host,port))
4.set the server in listening mode
server_socket.listen()
5.make new connection
connection,address = server_socket.accept()
6.Till server gets data from client maintain connection with client and send client data
while(True): data = connection.recv(1024).decode() if not data: break print("Message Recieved : " + str(data)) connection.send("Recieved your data".encode())
7.After all work close the socket
connection.close()
Client Side Code
1.set up the host
host = socket.gethostname()
2.set up the port
port = 3000
3.make socket instance
client_socket = socket.socket()
4.connect to server at particular host and port
client_socket.connect((host,port))
5.custom message
message = input("Enter the message : ")
6.write and send message till client does not type bye
while(message.lower().strip() != 'bye'):
client_socket.send(message.encode())
data = client_socket.recv(1024).decode()
print(f'Recieved : {data}')
message = input("Enter the message : ")
7.close the socket
client_socket.close()
#FINAL CODE
from pydoc import cli
import socket
def client():
host = socket.gethostname()
port = 3000
client_socket = socket.socket()
client_socket.connect((host, port))
message = input("Enter your message : ")
while message.lower().strip() != 'over&out':
client_socket.send(message.encode())
data = client_socket.recv(1024).decode()
print('Messge received from server: ' + data)
message = input("Enter your next message : ")
client_socket.close()
if __name__ == '__main__':
client()
from pydoc import cli
import socket
def server():
host = socket.gethostname()
port = 3000
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen()
conn, address = server_socket.accept()
print("Connected to: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print("Recieved data : " + str(data))
data = input('Enter the message for client : ')
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
server()
#Screenshots