一個類似但不同的問題:如何在Python中實現非阻塞套接字服務器
我有一個生成字符串的IRC客戶端。這個IRC客戶端使用一個鉤子來調用一個方法(somone_said),只要有人說什麼。我想通過套接字將此字符串發送到我的Flash客戶端。
我有在閃光工作的客戶端和在python服務器,但問題是,它的塊: 1),同時監聽,同時等待下一個消息將要產生
此客戶端的連接 2)阻止IRC客戶端響應其他輸入。
我想我需要在一個單獨的線程中創建我的套接字,但這會產生三個問題。 1)我的someone_said事件驅動方法如何訪問套接字 2)如果有人在沒有服務器客戶端連接時(監聽時)或客戶端已關閉連接時說什麼,該怎麼辦。 3)如何檢查線程是否活着,如果不打開新線程?
我阻止服務器代碼是這樣的:
# Echo server program
import socket
import sys
HOST = None # Symbolic name meaning all available interfaces
PORT = 7001 # Arbitrary non-privileged port
s = None
def startListening():
print "starting to listen"
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error as msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
try:
data = conn.recv(1024)
except:
print "cannot recieve data"
break
if not data:
break
print data
message = ""
while not "quit" in message:
message = raw_input('Say Something : ') # This will come from event driven method
try:
conn.sendall(message)
except Exception as exc:
print "message could not be sent"
break
conn.close()
print "connection closed"
while 1:
startListening()
的XChat的模塊Python腳本是這樣的(需要HexChat運行)
__module_name__ = "Forward Module"
__module_version__ = "1.0.0"
__module_description__ = "Forward To Flash Module by Xcom"
import sys
import xchat
def someone_said(word, word_eol, userdata):
# method called whenever someone speaks in IRC channel
username = str(word[0]) # From IRC contains the username string
message = str(word[1]) # From IRC contains the user message
sendString = username + " : " + message
send_to_server(sendString)
def send_to_server(message):
# send over socket method to be implemented here
xchat.hook_print('Channel Message' , someone_said)
我一直在敲我的頭這牆現在幾天。幫助我obi wan kenobi,你是我唯一的希望。
我添加了一些asyncore代碼,但該腳本在等待連接和發送之間仍然阻塞。這是不可接受的,因爲HexChat IRC客戶端在進行時需要做其他事情。 – Zac
Python提供了使用'socket.setblocking(0)'的能力,之後你的套接字將是非阻塞的。主要文檔在這裏是可用的(http://docs.python.org/2/howto/sockets.html#non-blocking-sockets),你也可以在這裏使用一些工具(http://pymotw.com/2/select /index.html)。 – Koreth
程序在偵聽客戶端連接或發送之間仍然掛起。我不能讓程序掛起/暫停,因爲它應該在同一時間做其他事情。 – Zac