在Python上聊天客户端/服务器问题 [英] Chat Client/Server problems on Python

查看:74
本文介绍了在Python上聊天客户端/服务器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的一个朋友正在使用python聊天室,基本上他是在做服务器部分,而我在做GUI和客户端部分,我不知道为什么该应用程序会停止工作而没有任何理由显示Windows消息 Python没有响应

Me and a friend of mine are doing a chat room with python, basically he's doing the server part and I'm doing the GUI and Client part, I don't know why the app just stop to work without any reason showing the Windows message "Python is not responding"

这是服务器代码:

#max name length=9999
#max message types=100
#max groupmsg recipients = 9999
#max msg length =8191 characters

import socket
import threading
import sys

def find_users(): #Continously Searches For New Clients
   while True:
      user, client_address = connector.accept()
      threading.Thread(target=new_user, args=(user,)).start()

def new_user(identity):
    while True:
       print(identity)
       name_length=identity.recv(4).decode() #max user name length =9999
       username=identity.recv(int(name_length)).decode()
       password=identity.recv(8192).decode()
       if username in user_details and password == user_details[username]: #correct credentials
          client_details[usename]=identity
          identity.sendall('y'.encode())
          break

       elif username in user_details: #incorrect password
          print('Please Re-enter The User Details')
          identity.sendall('n'.encode())

       else: #New user
            user_details[username]=password
            client_details[username]=identity
            identity.sendall('y'.encode())
            break

    pubmsg(username+' has connected')
    active_users.append(username)
    identity.settimeout(5)

    try:
       while True: #waits for incoming messages
           msgtype= identity.recv(2).decode() #identifies message type, max types =100

           if msgtype == '01': #public message
              communication = identity.recv(8192).decode()
              pubmsg(str(username + ' >>> ' + communication))

           elif msgtype == '02': #private message
              direction=[]
              recipno=identitiy.recv(4) #defines max group msg recipients
              for y in range(0,recipno): #repeats once per recipient
                 recip_name_length=identity.recv(4).decode()
                 recip_name=identity.recv(recip_name_length).decode()
                 direction.append(recip_name)

              gmsg=identity.recv(8192).decode()
              groupmsg(gmsg,direction)

    except Exception as e:
       active_users.remove(username)
       del client_details[username]
       pubmsg(username+' disconnected')
       identity.close()
       sys.exit()

def pubmsg(Group_message):
   print(Group_message)
   for person in client_details:
      client_details[person].sendall(Group_message.encode())

def groupmsg(Direct_message,recipients,sender):
    gmsg=sender +' (to '
    for person in recipients: #repeats once per recipient
        gmsg+=person+', '

    gmsg=gmsg.rstrip(', ')
    gmsg=gmsg + ')' + ' >>> ' + Direct_message

    for person in recipients:
        client_details[person].sendall(gmsg)

user_details={}
client_details={}
active_users=[]

connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Launching Server')
connector.bind(('localhost', 5000)) #Links socket to server address

connector.listen(10)
threading.Thread(target=find_users).start()

对于客户端和GUI,我仅将GUI按钮连接所调用的功能放在此处(即会产生问题),GUI使用QT库

For the client and the GUI I'm putting here only the function called by the button "Connect" of the GUI (the ones that are creating problems), the GUI uses the QT Libraries

这是按钮调用的代码:

def client_connect(self):
        ip_address = str(self.ipText.toPlainText())
        port = int(self.portText.toPlainText())
        nickname = self.nameText.toPlainText()
        password = 'hello'

        connect = threading.Thread(target = connection_thread, args = (ip_address, port, nickname, password))
        connect.start()

这是线程函数:

def connection_thread(address, port, nickname, password):
        nickname = nickname.encode()
        password = password.encode()
        while True:
                try:
                        c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        c.connect((address, port))
                        c.sendall('{0:0=4d}'.format(len(nickname)).encode())
                        c.sendall(nickname)
                        c.sendall(password)
                        answr = c.recv(2).decode()
                        if answr == 'y':
                                msg_box("CONNECTED", "Now you are connected to the server.")
                                while True:
                                        time.sleep(2)
                                        c.sendall('03'.encode())
                                        message_received =c.recv(8192).decode()
                                        self.chatList.addItem(message_received)
                except Exception as e:
                        msg_box("CONNECTION FAILED", "Connection to server failed, try again.")
                        break

从服务器代码到达我的客户端的连接,但是,该客户端停止工作,而没有显示表明我们已连接的msg_box。

From the server code the connection of my client arrives but, the client stop working without showing the msg_box that says that we are connected.

推荐答案

当您说 connect.join()时,您等待线程 connect 完成,但是它处于无限循环中,因此直到连接关闭才完成。

When you say connect.join() you wait for the thread connect to finish, but it is in an infinite loop, so it is not done until the connection closes.

这篇关于在Python上聊天客户端/服务器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆