Python:在线程之间同步输入和输出

时间:2009-12-21 14:31:40

标签: python input multithreading

目前,我正在尝试用Python中的套接字做一个小项目,这是一个双用户聊天系统。

import socket
import threading

#Callback. Print doesn't work across threads
def data_recieved(data):
    print data

#Thread class to gather input
class socket_read(threading.Thread):
    sock = object
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock
    def run(self):
        while True:
            data = self.sock.recv(1000)
            if (data == "\quitting\\"):
                return
            data_recieved(self.sock.recv(1000))

####################################################################################
server = False
uname = input("What's your username: ")
print "Now for the technical info..."
port = input("What port do I connect to ['any' if first]: ")
#This is the first client. Let it get an available port
if (port == "any"):
    server = True
    port = 9999
    err = True
    while err == True:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(('', port))
            err = False
        except:
            err = True
        sock.close()

    print "Bound to port #" + str(port)
    print "Waiting for client..."

    sock.listen(1)
    (channel, info) = sock.accept()
else:
    #This is the client. Just bind it tho a predisposed port
    host = input("What's the IP of the other client: ")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, int(port)))

msg = ""
if (server == True):
    #Use the connection from accept
    reader = socket_read(channel)
else:
    #Use the actual socket
    reader = socket_read(sock)
reader.start()
while msg != 'quit':
    #Get the message...
    msg = uname + ": " + input("Message: ")
    try:
        #And send it
        if (server == True):
            #Use the connection from accept
            channel.send(msg)
        else:
            #Use direct socket
            sock.send(msg)
    except:
        break
reader.join()
channel.send("\quitting\\")
sock.close()

(我希望评论有所帮助)

无论如何,通过同时调用输入,并获取另一个套接字的消息,我有一个小的同步问题。我可以连接,但是当我收到消息时,它不会取消输入语句。

换句话说,当我收到一条消息时,它会说这个

Message: user: I got a message
#Flashing cursor here 

因此它不会取消输入语句。

另外,我只收到所有其他消息。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

这里的内容不是同步问题,而是演示文稿/ UI问题。我建议让你的生活更轻松,并选择一些UI工具包(curses,wxPython,pyqt)来处理与用户的交互。使用input()对于快速而肮脏的一次性代码非常方便,但它不是很复杂。

如果你这样做,你会发现你根本不需要使用线程(通常就是这种情况),你的问题会像神奇的一样消失!

答案 1 :(得分:1)

好的,对不起对我自己的问题这么快的回答,但是在使用线程时回调是神奇的(至少在Linux的模型上)。

无论如何,做到了这一点:

import socket
import threading

def msg_loop(socket):
    msg = ""
    if (server == True):
        reader = socket_read(channel)
    else:
        reader = socket_read(sock)
    reader.start()
    while msg != 'quit':
        msg = uname + " said : " + input("Message: ")
        print ""
        try:
            if (server == True):
                channel.send('null')
                channel.send(msg)
            else:
                sock.send('null')
                sock.send(msg)
        except:
            break

def data_recieved(data, socket):
    print "Hold on...\n\n" + data + "\n"
    msg_loop(socket)

class socket_read(threading.Thread):
    sock = object
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock
    def run(self):
        while True:
            data = self.sock.recv(1000)
            if (data == "\quitting\\" or data == ''):
                return
            data_recieved(self.sock.recv(1000), self.sock)

####################################################################################
server = False
uname = str(input("What's your username: "))
print "Now for the technical stuff..."
port = input("What port do I connect to ['any' if first]: ")
if (port == "any"):
    server = True
    port = 9999
    err = True
    while err == True:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(('', port))
            err = False
        except:
            print "Socket #" + str(port) + " failed"
            err = True
            sock.close()
            port -= 1

    print "Bound to port #" + str(port)
    print "Waiting for client..."

    sock.listen(1)
    (channel, info) = sock.accept()
else:
    host = input("What's the IP of the other client: ")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, int(port)))

if (server == True):
    msg_loop(channel)
else:
    msg_loop(sock)

reader.join()
channel.send("\quitting\\")
sock.close()

如您所见,我将消息循环添加为回调。

另请注意,我发送一个空值,以规避“其他”问题。

那,我在data_recieved打印结束时使用换行符来禁用换行符。

(如果您喜欢这些代码,它在Windows上运行得不好。这是因为,显然,Python的线程模型并没有那么苛刻地执行。在您的本地Linux机器上试用它)