我在端口5555上运行了一个echo服务器,它接收并完美地返回数据,但它不会正确关闭。当我输入退出命令时,它只是保持打印空白输出。有人可以帮忙,谢谢。
Keeps printing received data (which is empty)
Server_side代码
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代码
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()
答案 0 :(得分:1)
当您在发送消息之前突破客户端的while循环(在退出输入的情况下)时,服务器永远不会收到关闭命令。这意味着客户端将在关闭服务器的同时关闭。
解决此问题的一个选项是切换邮件发送到服务器的顺序(发送,然后检查以关闭客户端)
client_socket.send(message.encode())
if message.lower() == 'quit':
break
希望这会有所帮助