如何使用线程和队列处理聊天客户端?

0 投票
1 回答
1124 浏览
提问于 2025-04-17 18:25

我现在遇到的问题是关于一个聊天客户端的,这个客户端我已经尝试了好几天想让它正常工作。这个客户端是我原来的聊天客户端的升级版,原来的那个只能在收到消息后才能回复别人。

所以我在咨询了一些人并做了一些研究后,决定使用select.select来处理我的客户端。

问题是,它还是和以前一样有问题。

*循环在接收消息时卡住,直到收到消息才会继续执行*

这是我目前写的代码:

import select
import sys #because why not?
import threading
import queue

print("New Chat Client Using Select Module")

HOST = input("Host: ")
PORT = int(input("Port: "))

s = socket(AF_INET,SOCK_STREAM)

print("Trying to connect....")
s.connect((HOST,PORT))
s.setblocking(0)
# Not including setblocking(0) because select handles that. 
print("You just connected to",HOST,)

# Lets now try to handle the client a different way!

while True:
    #     Attempting to create a few threads
    Reading_Thread = threading.Thread(None,s)
    Reading_Thread.start()
    Writing_Thread = threading.Thread()
    Writing_Thread.start()



    Incoming_data = [s]
    Exportable_data = []

    Exceptions = []
    User_input = input("Your message: ")

    rlist,wlist,xlist = select.select(Incoming_data,Exportable_data,Exceptions)

    if User_input == True:
        Exportable_data += [User_input]

你可能在想我为什么会用到线程和队列。

这是因为有人告诉我可以通过使用线程和队列来解决这个问题,但我看了文档,找了视频教程或者例子,还是完全不知道怎么用它们来让我的客户端正常工作。

有没有人能帮帮我?我只需要找到一种方法,让客户端可以随时发送消息,而不需要等着回复。这只是我尝试的其中一种方法。

1 个回答

1

通常,你会创建一个函数,在这个函数里运行你的 While True 循环,并且可以接收数据。然后,这些数据可以写入一个缓冲区或队列,这样你的主线程就能访问这些数据。

你需要确保对这个队列的访问是同步的,以避免数据竞争的问题。

我对Python的线程处理不太熟悉,不过创建一个在线程中运行的函数应该不难。让我找个例子。

其实你可以创建一个类,这个类里面有一个函数,并且这个类是从 threading.Thread 继承来的。然后你可以创建这个类的实例,并以这种方式启动线程。

class WorkerThread(threading.Thread):

    def run(self):
        while True:
            print 'Working hard'
            time.sleep(0.5)

def runstuff():
    worker = WorkerThread()
    worker.start() #start thread here, which will call run()

你也可以使用一个更简单的接口,创建一个函数,然后调用 thread.start_new_thread(fun, args),这样就会在一个线程中运行这个函数。

def fun():
    While True:
        #do stuff

thread.start_new_thread(fun) #run in thread.

撰写回答