# 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(1024)
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 = 111
receiverPort=ioPort
toName = 'localhost'
if len(sys.argv)>1 : toName = sys.argv[1]
if toName == 'localhost' : receiverPort = 222
try :
ioSocket.bind(('',ioPort))
except Exception, msg :
ioPort = 222
receiverPort = 111
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()
|