简体   繁体   English

如何处理 python 中损坏的 pipe 错误? (套接字编程)

[英]How to handle broken pipe error in python? (socket programming)

In these codes, I'm comparing messages received from clients with text content in a file.在这些代码中,我将从客户端收到的消息与文件中的文本内容进行比较。 When compiled, it works as expected with correct password and username, but with the wrong password, connection.send(str.encode('Password: ')) will return a broken pipe error.编译后,它使用正确的密码和用户名按预期工作,但使用错误的密码, connection.send(str.encode('Password: '))将返回损坏的 pipe 错误。 What did I do wrong here?我在这里做错了什么?

  # user can try 5 times
  while retryCounter < 5:
      if name == check[0] and newPassword != check[1]:
          connection.send(str.encode('> Invalid Password, please try again. \n')) 
          connection.send(str.encode('Password: '))
          newPassword = connection.recv(2048).decode()
          retryCounter = retryCounter + 1
          print(retryCounter)
          if name == check[0] and newPassword == check[1]:
              connection.send(str.encode(f'> Login Successful! \n')) 
              connection.send(str.encode(f'> Welcome to TOOM, {name}.\n'))
              connection.send(str.encode(f'> Enter one of the following commands (MSG, DLT, EDT, RDM, ATU, OUT, UPD):\n'))
              break
          if retryCounter == 4:
              connection.send(str.encode('> You are blocked! '))

also the client side code:还有客户端代码:

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect the client
client.connect((host, port))
response = client.recv(2048)
# Input UserName
name = input(response.decode()) 
client.send(str.encode(name))
response = client.recv(2048)
# Input Password
password = input(response.decode()) 
client.send(str.encode(password))
''' Response : Status of Connection :
    1 : Registeration successful 
    2 : Login Successful
    3 : Login Failed (wrong password)
'''
# Receive response 
response = client.recv(2048)
response = response.decode()

print(response)
client.close()

The server expect the client to retry the password if failed.如果失败,服务器希望客户端重试密码。 But the client does not retry the password.但客户端不会重试密码。 Instead the client closes the connection no matter if login was successful or not.相反,无论登录是否成功,客户端都会关闭连接。 When the server asks again for the password it will now write to a socket closed by the client - which will cause Broken Pipe.当服务器再次询问密码时,它现在将写入客户端关闭的套接字 - 这将导致 Broken Pipe。

The fix is to align the expectations of the server with what the client is actually doing, ie either don't expect the client to retry at the server side or actually retry a failed login on the client side.解决方法是使服务器的期望与客户端实际执行的操作保持一致,即不要期望客户端在服务器端重试或实际上在客户端重试失败的登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM