gpt4 book ai didi

python - 如何使用另一个类初始化 python 线程套接字服务器?

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:09 25 4
gpt4 key购买 nike

我正在编写一个 python irc 机器人,我想添加一个 tcp 服务器,以便机器人可以回显在 irc channel 中发送给它的消息。我正在使用 python socketserver 模块,以便它支持 linux 和 freebsd (我都使用)。我这里有一个简短的测试脚本:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import socketserver
from threading import Thread


class announce():
""" Return message uppercase """
def uppercase(message):
print (message.upper())

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" Echo data back in uppercase """
def handle(self):
self.announce = announce
data = str(self.request.recv(1024), 'utf-8')
if data is not None:
self.announce.uppercase(data)
self.request.send(bytes("message recieved", 'utf-8'))
self.request.close()

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True

def __init__(self, server_address, RequestHandlerClass):
socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)

if __name__ == "__main__":
HOST = "localhost"
PORT = 2000
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.shutdown()
server.server_close()

我想要做的是让 irc 机器人启动 tcp 服务器,并让 tcp 服务器将其收到的任何数据发送给机器人。

完整的(非工作的)机器人代码在这里:https://github.com/meskarune/autobot/blob/master/src/autobot.py

以下是包含相关部分的删节版本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class AutoBot(irc.bot.SingleServerIRCBot):
"""Create the single server irc bot"""
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read("autobot.conf")

self.nick = self.config.get("irc", "nick")
self.nickpass = self.config.get("irc", "nickpass")
self.name = self.config.get("irc", "name")
self.network = self.config.get("irc", "network")
self.port = int(self.config.get("irc", "port"))
self._ssl = self.config.getboolean("irc", "ssl")
self.channel_list = [channel.strip() for channel in self.config.get("irc", "channels").split(",")]
self.prefix = self.config.get("bot", "prefix")

if self._ssl:
factory = irc.connection.Factory(wrapper=ssl.wrap_socket)
else:
factory = irc.connectionFactory()
try:
irc.bot.SingleServerIRCBot.__init__(self, [(self.network, self.port)],
self.nick, self.name,
reconnection_interval=120,
connect_factory = factory)
except irc.client.ServerConnectionError:
sys.stderr.write(sys.exc_info()[1])

#Listen for data to announce to channels
self.listenhost = self.config.get("tcp", "host")
self.listenport = int(self.config.get("tcp", "port"))
TCPinput(self.connection, self, self.listenhost, self.listenport)

def announce(self, connection, text):
"""Send notice to joined channels"""
for channel in self.channel_list:
self.connection.notice(channel, text)
self.log_message(channel, "-!-", "(notice) {0}: {1}"
.format(self.connection.get_nickname(), text))
class TCPinput():
"""Listen for data on a port and send it to Autobot.announce"""
def __init__(self, connection, AutoBot, listenhost, listenport):
self.connection = connection
self.AutoBot = AutoBot
self.listenhost = listenhost
self.listenport = listenport
server = ThreadedTCPServer((self.listenhost, self.listenport), ThreadedTCPRequestHandler)
try:
server.serve_forever()
except:
server.shutdown()
server.server_close()
def send(self, message):
self.AutoBot.announce(self.connection, message.strip())

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" Echo data back in uppercase """
def handle(self):
self.TCPinput = TCPinput
data = str(self.request.recv(1024), 'utf-8')
if data is not None:
self.TCPinput.send(data.strip())
self.request.close()

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True

def __init__(self, server_address, RequestHandlerClass):
socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)

def main():
bot = AutoBot()
bot.start()

if __name__ == "__main__":
main()

使用当前代码,机器人在运行时挂起,当我执行 ctrl-c 时,它会连接然后崩溃。我真的很想知道如何才能让它发挥作用。谢谢。

最佳答案

TCPinput内,您在主控制线程中调用serve_forever,导致其阻塞。相反,您需要在单独的线程中运行服务器。您可以通过从 threading.Thread 派生 TCPinput 来实现此目的,并在初始化对象时将 serve_forever 设置为线程目标。然后,在初始化机器人时,您可以 Thread.start() 该线程。

关于python - 如何使用另一个类初始化 python 线程套接字服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com