chat3.py

Document last modified: 

Adds resend of any chat received from another chatter to all chatters in list except sender of the chat  (Download). Message loops occur if chat sent to back to chatter.
 

 

# chat3

from socket import *
import threading, sys

class receiver(threading.Thread) :
    def __init__(self, socket, chatList, receiverPort ):
        threading.Thread.__init__(self)
        self.SOCKET=socket
        self.CHATLIST = chatList
        self.setDaemon(True)

        self.RECEIVERPORT = receiverPort

    def run(self) : # Add new chatters to list
        while True : # forward any chat received
             data, (fromName, port) = self.SOCKET.recvfrom(10240)
             if not data : break
             print fromName, ': ', data, ' ', chatList
             if fromName not in self.CHATLIST : self.CHATLIST[:0] = [fromName]

        for toName in self.CHATLIST :
              if toName != fromName :
                 self.SOCKET.sendto(data, (toName, self.RECEIVERPORT))

        self.SOCKET.close()

ioSocket=socket(AF_INET, SOCK_DGRAM)
ioPort = 11111
receiverPort=ioPort
toName = 'localhost'

if len(sys.argv)>1 : toName = sys.argv[1]
if toName == 'localhost' : receiverPort = 22222

try :
    ioSocket.bind(('',ioPort))
except Exception, msg :
    ioPort = 22222
    receiverPort = 11111
    ioSocket.bind(('',ioPort))

print 'chat3 on port ', ioPort, '. Blank line to quit.'

chatList=[toName]

receiver(ioSocket, chatList, receiverPort).start()

while True : # Send in main thread
    userIn = raw_input() # any user input to all chatters
    if not userIn : break
    for name in chatList :
        ioSocket.sendto(userIn, (name, receiverPort))
ioSocket.close()