我正在努力让我的 python 套接字正常运行。
有两个主要问题:
1)当它侦听客户端连接时,程序停止,这是一个问题,因为它在 IRC 客户端 python 解释器上运行,导致 IRC 客户端在客户端连接之前不响应。
2)当客户端断开连接时,整个脚本必须停止,然后再次重新启动,以便让套接字服务器再次监听。
我认为解决方法可能是在单独的线程中启动套接字侦听,因此 IRC 客户端可以在等待客户端连接时继续。此外,一旦客户端决定关闭连接,我需要一种重新启动它的方法。
以下代码很糟糕并且不起作用,但它可能会让您对我正在尝试的内容有所了解:
__module_name__ = "Forward Module"
__module_version__ = "1.0.0"
__module_description__ = "Forward To Flash Module by Xcom"
# Echo client program
import socket
import sys
import xchat
import thread
import time
HOST = None # Symbolic name meaning all available interfaces
PORT = 7001 # Arbitrary non-privileged port
s = None
socketIsOpen = False
def openSocket():
# start server
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'
global socketIsOpen = False
sys.exit(1)
conn, addr = s.accept()
print 'Connected by', addr
global socketIsOpen = True
def someone_said(word, word_eol, userdata):
username = str(word[0])
message = str(word[1])
sendMessage = username + " : " + message
send_to_server(sendMessage)
def send_to_server(message):
conn.send(message)
def close_connection():
conn.close()
print "connection closed"
xchat.hook_print('Channel Message' , someone_said)
def threadMethod(arg) :
while 1:
if (not socketIsOpen) :
openSocket()
try:
thread.start_new_thread(threadMethod, args = [])
except:
print "Error: unable to start thread"
python 在一个名为 HexChat 的 IRC 客户端上运行,这是 xchat 导入的来源。