我正在努力让我的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导入的来源。
答案 0 :(得分:1)
通常编写线程套接字服务器的方式是:
accept()
一个非常小的例子就像这样:
import socket
import threading
import time
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 9999))
server.listen(1)
def handle(conn):
conn.send(b'hello')
time.sleep(1) # do some "heavy" work
conn.close()
while True:
print('listening...')
conn, addr = server.accept()
print('handling connection from %s' % (addr,))
threading.Thread(target=handle, args=(conn,)).start()
您正在生成新线程,您可以在其中创建侦听套接字,然后接受并处理您的连接。虽然socketIsOpen
是True
,但您的程序将通过while循环使用大量的cpu循环。 (顺便说一句,你检查socketIsOpen
的方式允许竞争条件,你可以在设置之前启动多个线程。)
最后一件事,您应该尝试使用threading
模块而不是弃用的thread
。