Reputation: 3
I made a echo server run on port 5555 and it receives and returns data perfectly but it will not close correctly. When i enter the exit command, it just keeps printing blank output. Can someone please help, thanks.
Keeps printing received data (which is empty)
Server_side code
import socket as sk
server_socket = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
server_socket.setsockopt(sk.SOL_SOCKET, sk.SO_REUSEADDR, 1)
server_socket.bind(("localhost", 5555))
server_socket.listen(1)
connection, client_address = server_socket.accept()
while True:
data_in = connection.recv(1024)
message = data_in.decode()
message.strip()
if message == "quit" or message == "QUIT":
break
print("" , message)
data_out = message.encode()
connection.send(data_out)
connection.shutdown(sk.SHUT_RDWR)
connection.close()
server_socket.shutdown(sk.SHUT_RDWR)
server_socket.close()
Client_side code
import socket as sk
client_socket = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
client_socket.connect(('localhost', 5555))
while True:
#input message
message = input("Enter message to send or type quit to quit: ")
#check if user wants to quit
if message == "quit" or message == "QUIT":
break
#encode the user input and send it to the server
client_socket.send(message.encode())
#save the data sent by the server
recmess = client_socket.recv(1024)
#print the server reply
print("Server: ", recmess.decode())
print()
#print student details
print("Connection Closed")
client_socket.shutdown(sk.SHUT_RDWR)
client_socket.close()
Upvotes: 0
Views: 62
Reputation: 98
As you are breaking out of the while loop on the client side (in the case of the quit input) prior to sending the message, the server never receives the command to shut down. This means the client will close down while leaving the server up.
One option to fix this issue is to switch the order in which the message is sent to the server (send, then check to close client side)
client_socket.send(message.encode())
if message.lower() == 'quit':
break
Hopefully this helps
Upvotes: 1