The codes below represent the server-side and client-side communication over TCP sockets. On the server side, a
Question:
The codes below represent the server-side and client-side communication over TCP sockets. On the server side, a socket object is created of type SOCK_STREAM (TCP socket), and bound to localhost IP (127.0.0.1) at port 5555. The socket then starts listening for incoming connections.
On the client side, a socket object is created of type SOCK_STREAM (TCP socket), and is used to connect to the server running at localhost IP (127.0.0.1) at port 5555. Once the connection is established, they can start sending and receiving messages.
Server-side code
import socket
import sys
import os
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_IP = '127.0.0.1'
server_port = 5555
server_sock.bind((server_IP, server_port))
server_sock.listen(1)
print('Listening for incoming connection... ')
while True:
connection, addr = server_sock.accept()
message = connection.recv(1024).decode()
print("message received from client at address: ", addr, message)
print("sending message back to client...", "")
connection.send(message.encode())
connection.close()
Client-side code
import socket
import sys
import os
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.connect(('127.0.0.1', 5555))
message = input("enter message to send: ")
client_sock.send(message.encode())
received_message = client_sock.recv(1024)
print("Received from server: ", received_message.decode())
client_sock.close()
Tasks:
Modify the codes to implement an ongoing chat session between the server and the client.
The chat session will prompt the client to send a message to the server, and upon receipt at the server, will prompt the server to reply to the client. The cycle will keep
repeating unless one ends up closing the connection.