似ているが異なる質問:
文字列を生成する IRC クライアントがあります。この IRC クライアントは、誰かが何かを言うたびにフックを使用してメソッド (somone_said) を呼び出します。この文字列をソケット経由でフラッシュ クライアントに送信したいと考えています。
私はフラッシュで動作しているクライアントとPythonでサーバーを持っていますが、問題はそれがブロックされることです:1)クライアント接続をリッスンしている間2)次のメッセージが生成されるのを待っている間
これにより、IRC クライアントが他の入力に応答しなくなります。
別のスレッドでソケットを作成する必要があると思いますが、これによりさらに 3 つの問題が発生します。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)
私はここ数日、この壁に頭をぶつけています。助けてオビワン・ケノービ、あなただけが私の希望です。