In: Computer Science
Write two python codes for a TCP client and a server using a Socket/Server Socket. The client sends a file name to the server. The server checks if there is any integer value in the file content. If there is an integer number, the server will send a message to the client “Integer exists” otherwise, the message “Free of Integers”
We send the file name "test.txt" to the server. The server reads the file, and sends the response appropriately.
Code server.py:
import socket
# take the server name and port name
host = 'local host'
port = 5000
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
c, addr = s.accept()
filename = c.recv(1024).decode()#receiving the filename from the client
value = "Free of Integers"
f = open(filename,'r')
while True:
#read by character
char = f.read(1)
if not char:
break
if(char.isdigit()):
value = "Integer exists"
break
#sending response to client
c.send(value.encode())
# disconnect the server
c.close()
Code client.py :
import socket
# take the server name and port name
host = 'local host'
port = 5000
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
filename = "test.txt"#file name to be sent to the server
s.send(filename.encode())
# receive message string from
# server, at a time 1024 B
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print(msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()
File:
Output: