Instructions
- 1
Create a socket object and bind it to a port so that it may listen for incoming messages:
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind(('127.0.0.1',5432))
soc.listen(5)
Define the class to receive messages. This relies on the "threading" library so that it can run in the background of other applications:
class ChatThread(threading.Thread):
def __init__(self,c):
threading.Thread.__init__(self)
self.conn = c
self.stopIt=False
3 Define the "run" method, which executes when a thread of type "ChatThread" executes:
def run(self):
while not self.stopIt:
msg = self.message_recv()
print 'recieved-> ',msg
4 Define a message receiving class, which runs as part of the "run" method. This waits for messages and returns the message once received:
def message_recv(self):
data = self.conn.recv(SIZE)
self.conn.send('OK')
msg = self.conn.recv(int(data))
return msg
5 Get a socket connection and create a ChatThread thread:
c1,a1 = soc.accept()
thr = ChatThread(c1)
thr.start()
sender = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind(('127.0.0.1',5433))
sender.send('Message')
No comments:
Post a Comment