【问题标题】:How to handle chat client using threading and queues?如何使用线程和队列处理聊天客户端?
【发布时间】:2013-02-24 04:36:57
【问题描述】:

我现在遇到的问题是关于这个聊天客户端的问题,我已经尝试了好几天了。应该是我原来的聊天客户端的升级版,只有先收到消息才能回复人。

所以在四处询问和研究人员之后,我决定使用 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]

您可能想知道为什么我有线程和队列。

那是因为人们告诉我,我可以通过使用线程和队列来解决问题,但是在阅读文档之后,寻找与我的案例相匹配的视频教程或示例。我仍然完全不知道如何使用它们来使我的客户工作。

有人可以帮我吗?我只需要找到一种方法让客户尽可能多地输入消息,而无需等待回复。这只是我尝试的方法之一。

【问题讨论】:

    标签: python multithreading chat


    【解决方案1】:

    通常您会创建一个函数,您的 While True 循环在其中运行并可以接收数据,它可以将数据写入您的主线程可以访问的某个缓冲区或队列。

    您需要同步对该队列的访问以避免数据争用。

    我对 Python 的线程 API 不太熟悉,但是创建一个在线程中运行的函数并没有那么难。让我找一个例子。

    事实证明,您可以创建一个具有函数的类,该类派生自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()
    

    您还可以使用更简单的 API 并创建一个函数并在其上调用 thread.start_new_thread(fun, args),这将在线程中运行该函数。

    def fun():
        While True:
            #do stuff
    
    thread.start_new_thread(fun) #run in thread.
    

    【讨论】:

    • 要是我知道什么是类或函数就好了。也许我应该放弃。我已经什么都不知道了。文档对我来说 100% 无效。
    • @Xeon 一个类只是定义某种类型的一种方式。它描述了类型有什么以及可以对该类型进行哪些操作。一个班级人,可能有成员姓名、地址等,可能有一个叫“goHome”或“work”的操作。
    • 我还是不明白发生了什么。它是如此令人沮丧,因为它已经 2 天寻找修复,我现在只是绝望。即使有你的帮助,我也不知道我在做什么。甚至如何使用它。我需要一本书。或适当的教程链接。我到处找,什么也找不到。
    • 您遇到的具体问题是什么?
    • 我遇到的问题是我不明白我应该如何将线程和队列与我当前的问题集成。人们告诉我这是解决方案。但除此之外,我完全不知道如何使它工作。我尝试制作几个线程,但后来我不知道我应该对线程做什么,如何将它与我的输入集成。如何使 select.select 在我的回复准备好发送时发送。它甚至如何解决我目前的问题,即我被困在等待接收数据。而且它越来越模糊
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 2015-07-03
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多