在客户端用 Python 创建聊天应用程序,但有几个问题我无法弄清楚

问题描述 投票:0回答:1

第一期:

套接字过早关闭。 如果用户提供了唯一的用户名,它会正确接受。 但是,如果用户提供的用户名已被使用,则会显示“重试消息”,并要求用户输入新的用户名,但是因为套接字在用户输入新用户名后过早关闭,“来自服务器的意外响应”显示消息,然后提示用户在弹出错误之前再次输入新用户名([Errno 31] broken pipe)。

第二期:

当用户输入“!who”时,所有当前登录用户的列表会正确显示。但是,列表显示后,用户无法再与服务器交互。没有错误弹出,但服务器变得无响应。

第三期:

在用户输入“!quit”之后什么也没有发生。但是,如果用户在所有当前登录用户的列表弹出后立即输入“!who”,那么这意味着用户实际上并没有关闭客户端。

代码:

import socket
import threading
import sys

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

host_port = ("143.47.184.219", 5378)
client_sock.connect(host_port)

# use this to shut down the client???
# def close():
#     server.shutdown(socket.SHUT_RDWR)
#     server.close()
#     print ("closed")

# request unique username from user

while True:
  user_name = input('Enter a unique user name: ')
  message = 'HELLO-FROM {}\n'.format(user_name)
  client_sock.send(message.encode())
  response = client_sock.recv(4096).decode()

  if response.startswith('HELLO '):
    print('You are logged in as {}'.format(response[6:].strip()))
    break

  elif response == 'IN-USE\n':
    print('That username is already in use. Please input an alternative.')

  elif response == 'BUSY\n':
    print(
      'The maximum number of clients has been reached. Please try again later.'
    )
    sys.exit()

  else:
    print('Unexpected response from server.')

  break

user requests list of all currently logged in users

  while True:
  list_request = input()
  if list_request == '!who':
    message1 = 'LIST\n'
    client_sock.sendall(message1.encode())
    response = client_sock.recv(4096).decode()
    if response.startswith('LIST-OK '):
      print('Here is a list of all currently logged in users: {}'.format(response[8:].strip()))
      break

# user asks to shut down the client

while True:
  quit_request = input()
  if quit_request == '!quit':
    sys.exit()

# while True:
#   shutdown_request = input()
#   if shutdown_request == '!quit':
#     close()
#     exit(0)
#     print('Chat clinet has been shutdown.')

# function recieves messages from other users and displays them to the user

def receive():
    while True:
        try:
            # Waiting until data comes in
            # Receive at most 4096 bytes
            data = client_sock.recv(4096).decode()
            if not data:
                    print("Socket is closed.")
            else:
                    print("Socket has data.")
        except OSError as msg:
            print(msg)
            socket.close()
            break

# all possible inputs

# while True:
#   user_input = input(user_name + ': ')

#   if user_input == '!who':
#     message = 'LIST\n'
#     client_sock.sendall(message.encode())
#     response = client_sock.recv(4096).decode()
#     if response.startswith('LIST-OK '):
#       print('Here is a list of all currently logged in users: {}'.format(
#         response[8:].strip()))
#       break

#   if user_input == '!quit':
#     message = shutdown()
#     print('Chat client has been shutdown')

仍在尝试弄清楚如何关闭客户端并防止套接字过早关闭。

python sockets tcp python-multithreading
1个回答
0
投票

第一期

在你所有的 if 语句之后,你调用 break。这将退出 while 循环。像这样删除 while 循环中的第二个中断:

while True:
  user_name = input('Enter a unique user name: ')
  message = 'HELLO-FROM {}\n'.format(user_name)
  client_sock.send(message.encode())
  response = client_sock.recv(4096).decode()

  if response.startswith('HELLO '):
    print('You are logged in as {}'.format(response[6:].strip()))
    break

  elif response == 'IN-USE\n':
    print('That username is already in use. Please input an alternative.')

  elif response == 'BUSY\n':
    print(
      'The maximum number of clients has been reached. Please try again later.'
    )
    sys.exit()

  else:
    print('Unexpected response from server.')

第二期

我要假设:

user requests list of all currently logged in users

  while True:

是格式错误。在这种情况下,while 循环属于与问题 1 相同的问题:

  while True:
  list_request = input()
  if list_request == '!who':
    message1 = 'LIST\n'
    client_sock.sendall(message1.encode())
    response = client_sock.recv(4096).decode()
    if response.startswith('LIST-OK '):
      print('Here is a list of all currently logged in users: {}'.format(response[8:].strip()))

第三期

你提供的代码,鉴于一半被注释掉了,不能得出这个结论。应该发生的是,一旦用户请求表并成功接收到它,while 循环就会退出并开始另一个 while 循环,该循环一直运行到用户要求退出为止。

作为一般建议,在代码周围添加打印语句以找出代码停止的位置,这样您就可以找到计算机卡住的代码行。

© www.soinside.com 2019 - 2024. All rights reserved.