KekMeister Johhny
KekMeister Johhny

Reputation: 141

What is the best way to handle multiple socket connections

What I need to do is read x amount of accounts from a file based on the amount of lines and make x amount of individual sockets that I can manipulate as much as I like (send messages to IRC and anything else)

How I'm going about it as of now:

lines=tuple(open('accts.txt', 'r'))
for line in lines:
    data=line.split(' ',1)
    a=threading.Thread(target=Spawn,args=(data[0].replace('\n',''),data[1].replace('\n','')))
    a.start()

#s.send wont work here because it doesn't exist in this context

I tried to use threads but it seems threads don't allow you to access them from outside of the thread itself from what I understand

Must support a while True: in a thread but I can live w/o it if its not posible

Here is the Spawn function that was being created by the thread:

def Spawn(nick,password):
    Active=True

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(('irc.boats.gov',6667))
    s.send('PASS '+password+'\r\n')
    s.send('NICK '+nick+'\r\n')
    s.send('JOIN '+channel+'\r\n')

    while True:
        buf=s.recv(1024)
        if('PRIVMSG' in buf):
            sender=buf.split('!',1)[0].split(':')
            message=buf.split(':',2)[2].replace('\n','')
            if(sender[1]==owner):
                if(sender[1]==owner):
                    if(message.strip()=='!stop'):
                        Active=False
                        print '('+nick+')'+' has been disabled'
                    else:
                        if(message.strip()=='!start'):
                            Active=True
                            print '('+nick+')'+' has been enabled'
                        else:
                            if(Active):
                                print 'sent'

Upvotes: 3

Views: 318

Answers (1)

dkol
dkol

Reputation: 1469

If you want to create multiple connections you can do it like this:

from socket import *
SERVER       = ('irc.boats.gov',6667)  # Server address


# Open up connections
connections = []
with open('accts.txt', 'r') as f:
    for line in f:
        s = socket(AF_INET,SOCK_STREAM)
        s.connect(SERVER)
        connections.append(s)
        s.send('PASS '+password+'\r\n')
        s.send('NICK '+nick+'\r\n')
        s.send('JOIN '+channel+'\r\n')

Then you can do whatever you want with them with select module for example. Threads won't help much here and can even degrade performance. You could also try Twisted, as suggested or use multiple processes.

Here is a nice related read from David Beazley on concurrency, I adapted the code from it.

Upvotes: 1

Related Questions