【发布时间】:2014-06-13 14:07:05
【问题描述】:
我有一个通过套接字接收消息的 IRC 客户端。
通过这个客户端,我创建了几个连接到 twitch 上其他人聊天频道的机器人。 (这些是经过授权的,而不是垃圾邮件机器人!)。
每个机器人都是在一个单独的线程中创建的,该线程采用通道名称和一些其他参数。
我的问题是我的 IRC 套接字只能绑定到一个端口,它处理所有 IRC 消息,每条消息都有一个 #channel 字符串作为第三个字符串,将其定向到特定通道。这些消息可以在每个机器人内部处理,因为每个机器人都知道其频道的名称。
我的问题是;如何将通过套接字接收的字符串发送到多个线程?
import time
import socket
import threading
import string
import sys
import os
class IRCBetBot:
#irc ref
irc = None
def __init__(self,IRCRef,playerName,channelName,currencyName):
#assign variables
self.irc = IRCRef
self.channel = '#' + channelName
self.irc.send(('JOIN ' + self.channel + '\r\n') .encode("utf8"))
#create readbuffer to hold strings from IRC
readbuffer = ""
# This is the main loop
while 1:
##readbuffer## <- need to send message from IRC to this variable
for line in temp:
line=str.rstrip(line)
line=str.split(line)
if (len(line) >= 4) and ("PRIVMSG" == line[1]) and (self.channel == line[2]) and not ("jtv" in line[0]):
#call function to handle user message
if(line[0]=="PING"):
self.irc.send(("PONG %s\r\n" % line[0]).encode("utf8"))
def runAsThread(ircref,userName, channelName, currencyPrefix):
print("Got to runAsThread with : " + str(userName) + " " + str(channelName) + " " + str(currencyPrefix))
IRCBetBot(ircref,userName,channelName,currencyPrefix)
# Here we create the IRC connection
#IRC connection variables
nick = 'mybot' #alter this value with the username used to connect to IRC eg: "username".
password = "oauth:mykey" #alter this value with the password used to connect to IRC from the username above.
server = 'irc.twitch.tv'
port = 6667
#create IRC socket
irc = socket.socket()
irc.connect((server, port))
#sends variables for connection to twitch chat
irc.send(('PASS ' + password + '\r\n').encode("utf8"))
irc.send(('USER ' + nick + '\r\n').encode("utf8"))
irc.send(('NICK ' + nick + '\r\n').encode("utf8"))
# Array to hold all the new threads
threads = []
# authorised Channels loaded from file in real program
authorisedChannels = [["user1","#channel1","coin1"],["user2","#channel2","coin2"],["user3","#channel3","coin3"]]
for item in authorisedChannels:
try:
userName = item[0]
channelName = item[1]
currencyPrefix = item [2]
myTuple = (irc,userName,channelName,currencyPrefix)
thread = threading.Thread(target=runAsThread,args = myTuple,)
thread.start()
threads.append(thread)
time.sleep(5) # wait to avoid too many connections to IRC at once from same IP
except Exception as e:
print("An error occurred while creating threads.")
print(str(e))
#create readbuffer to hold strings from IRC
readbuffer = ""
# This is the main loop
while 1:
readbuffer= readbuffer+self.irc.recv(1024).decode("utf-8")
temp=str.split(readbuffer, "\n")
readbuffer=temp.pop( )
#
#Need to send readbuffer to each IRCBetBot() created in runAsThread that contains a while 1: loop to listen for strings in its __init__() method.
#
print ("Waiting...")
for thread in threads:
thread.join()
print ("Complete.")
我需要以某种方式将主循环中的读取缓冲区放入在单独线程中创建的每个 IRCBetBot 对象中吗?有什么想法吗?
【问题讨论】:
-
您是想将 readbuffer 发送到每个线程,还是只发送消息实际用于的线程?
-
这两种方法都可以,我只需要将消息发送到适当的线程,但可以在手头或线程中完成装配。我认为在线程中这样做可能会更好,因为它知道它是谁,即它的频道名称。
标签: python multithreading sockets python-3.x