I tried to write a client-server system in which the server is executing commands that the client sends to it.
There are 4 possible commands:
NAME - returns the server's name.
TIME - returns the current time.
RAND - returns a random number between 1 to 10.
EXIT - disconnects the server-client communication.
After one of the commands is executed - the server closes the client's and the server's sockets.
Is there a way to keep the connetion "opened" and to continue sendind commands?
I've already tried to remove the next lines from the server code:
client_socket.close()
server_socket.close()
Here's the server code:
import socket
import time
import random
def main():
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(1)
(client_socket, client_adress) = server_socket.accept()
client_input = client_socket.recv(1024).decode()
if client_input == 'TIME':
client_socket.send(str(time.asctime(time.localtime(time.time()))).encode())
elif client_input == 'NAME':
server_name = 'server2.6'
client_socket.send(server_name.encode())
elif client_input == 'RAND':
client_socket.send(str(random.randint(0, 10)).encode())
elif client_input == 'EXIT':
client_socket.close()
server_socket.close()
pass
else:
error_message = 'Not one of the options'
client_socket.send(error_message.encode())
client_socket.close()
server_socket.close()
if __name__ == '__main__':
main()
And here's the client code:
import socket
def main():
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
options = ['NAME', 'TIME', 'RAND', 'EXIT']
is_legal_option = False
while is_legal_option == False:
client_input = input('Enter your command (NAMETIMERANDEXIT): ')
if len(client_input) != 4:
print("The command must be 4 letters.")
continue
if client_input.isupper() == False:
upper_client_input = client_input.upper()
client_answer = input("If you meant: '" + upper_client_input + "', enter '1', else enter '2'")
if client_answer == '1':
client_input = upper_client_input
for x in options:
if client_input == x:
is_legal_option = True
break
if is_legal_option == False:
print("Not one of the options.")
my_socket.send(client_input.encode())
data = my_socket.recv(1024).decode()
print (data)
my_socket.close()
if __name__ == '__main__':
main()
question from:
https://stackoverflow.com/questions/65939409/can-i-program-a-server-which-doesnt-close 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…