0

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

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

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

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

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

4

1 回答 1

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.
于 2013-03-08T15:26:15.983 回答