目前,我正在嘗試使用Python中的套接字(一種雙用戶聊天系統)做一個小型項目。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
因此,它不會取消輸入語句。
此外,我只收到其他所有消息。
有什麼建議嗎?
次要注意事項:「received」拼寫錯誤,您使用的「回調」不僅不是回調(它只是一個常規的函數調用),而是沒用的......用打印替換該調用,您將得到相同的結果。最後,input()是危險的,因爲它在用戶輸入上調用eval():相反,使用raw_input()會更安全,這可以做你可能認爲input()所做的事情。 – 2009-12-21 15:10:40
感謝您的想法。我剛碰到一個逗號錯誤,這個錯誤是固定的。 – new123456 2009-12-21 15:34:27