Showing posts with label socket. Show all posts
Showing posts with label socket. Show all posts

Monday, May 16, 2011

How to create an Irc echo bot

The example shows how to connect to an irc server and how to read and send data from the server.
import socket

def reply(privmsg, socket):
 """ decode the string with message,
     something like ':nickname!~hostname PRIVMSG my_nickname :hi'
     and echoes the message received to nickname """
 nick = privmsg[1:privmsg.find('!')]
 msg = privmsg[privmsg.find(':',1,len(privmsg))+1:len(privmsg)] 
 socket.send('PRIVMSG '+nick+' :'+msg) # sending to the socket


print 'Connecting...'
s = socket.socket()
s.connect(('irc.freenode.net',6667)) #connection to the irc server
s.send('NICK GlowPy\n')
s.send('USER PythonBot my.host.name humm : My Real Name\n')

while True:
 data = s.recv(1024) # reading from the socket
 print data
 if data.find('PRIVMSG') > 0: # if the string is a message
  reply(data,s)
A conversation with the bot:
<JustGlowing> hi there!
<GlowPy> hi there!
<JustGlowing> how are you?
<GlowPy> how are you?

Friday, April 22, 2011

How to implement a multithread echo server

The example implement a multithread echo server. Every incoming request is handed off to a worker thread that will process the request.
import socket
import thread

def handle(client_socket, address):
 while True:
  data = client_socket.recv(512)
  if data.startswith("exit"): # if data start with "exit"
   client_socket.close() # close the connection with the client
   break
  client_socket.send(data) # echo the received string

# opening the port 1075
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(),1075))
server.listen(2)

while True: # listen for incoming connections
 client_socket, address = server.accept()
 print "request from the ip",address[0]
 # spawn a new thread that run the function handle()
 thread.start_new_thread(handle, (client_socket, address)) 
And now we can use telnet to communicate with the server application:
$ telnet localhost 1075
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
hi
echo this!
echo this!
exit
Connection closed by foreign host.