Commit 1833f32e authored by Taddeus Kroes's avatar Taddeus Kroes

Added asynchronuous chat client and old chat client.

parent 804145da
import asyncore, socket
from Queue import Queue
import re
class ChatClient(asyncore.dispatcher):
def __init__(self, host, port, nickname='Foo'):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
self.verified = False
self.authenticated = False
self.authentification_sent = False
self.nickname = nickname
self.send_queue = Queue()
self.send_buffer = ''
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
buf = ''
multi_line = False
response_format = False
while True:
chunk = self.recv(1)
if not chunk:
raise RuntimeError("socket connection broken")
if chunk in ['-','+']:
response_format = True
elif chunk == ':':
multi_line = True
elif chunk == '\n' and buf[-1] == '\r':
if not multi_line or buf[-3:] == '\r\n\r':
break
multi_line = False
buf += chunk
buf = buf[:-1]
print '< %s' % buf
if not self.verified:
self.verify_server(buf)
elif response_format:
self.parse_response(buf)
else:
self.parse_notification(buf)
def verify_server(self, buf):
match = re.match('^CHAT/(\d\.\d)/([^\x00-\x1F/:]+)$', buf)
if not match:
print 'Failed to verify connection'
sys.exit(-1)
print 'Connected to server, server version is', match.group(1)
self.verified = True
self.send_queue.put('CHAT')
def parse_response(self, buf):
if not self.authenticated:
if not self.authentification_sent:
self.send_queue.put('USER %s' % self.username)
self.authentification_sent = True
def parse_notification(self, buf):
pass
def writable(self):
return not self.send_queue.empty() or len(self.send_buffer)
def handle_write(self):
if not self.send_buffer:
self.send_buffer = self.send_queue.get() + '\r\n'
print '> %s' % self.send_buffer[:-1]
sent = self.send(self.send_buffer)
self.send_buffer = self.send_buffer[sent:]
if __name__ == '__main__':
client = ChatClient('ow150.science.uva.nl', 16897)
asyncore.loop()
import socket
from Queue import Queue
import threading
import sys
import re
class Client:
"""
Chat client
Chat client.
"""
MSGLEN = 512
def __init__(self):
def __init__(self, host, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.send_queue = Queue(['CHAT'])
self.connect(host, port)
self.sender = ClientThread(self)
self.sender.handle = ClientThread.send
self.sender.daemon = True
#self.sender.start()
self.receiver = ClientThread(self)
self.receiver.handle = ClientThread.receive
self.receiver.daemon = True
#self.receiver.start()
self.verified = False
# def __exit__(self):
# print 'End of program.'
#
# def __del__(self):
# sys.exit(0)
def connect(self, host, port):
self.sock.connect((host, port))
def send(self, msg):
def parse(self, buf):
if not self.verified:
match = re.match('^CHAT/(\d\.\d)/([^\x00-\x1F/:]+)$', buf)
if match:
print 'Connected to server, server version is', match.group(1)
print match.group(2)
self.verified = True
else:
print 'Failed to verify connection'
sys.exit(-1)
else:
pass
class ClientThread(threading.Thread):
"""
Send/receive thread for chat client.
"""
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
def run(self):
print 'Starting new client thread.'
while True:
self.handle(self)
def send(self):
if self.client.send_queue.empty():
return
msg = self.client.send_queue.get()
print '> %s' % msg
msg += '\r\n'
msglen = len(msg)
totalsent = 0
while totalsent < self.MSGLEN:
sent = self.sock.send(msg[totalsent:])
while totalsent < msglen:
sent = self.client.sock.send(msg[totalsent:])
if not sent:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def receive(self):
buf = ''
multi_line = False
response_format = False
while True:
chunk = self.sock.recv(1-len(msg))
chunk = self.client.sock.recv(1)
if not chunk:
raise RuntimeError("socket connection broken")
print '< %s' % chunk
if chunk in ['-','+']:
response_format = True
elif chunk == ':':
multi_line = True
elif chunk == '\n' and buf[-1] == '\r':
if not multi_line or buf[-3:] == '\r\n\r':
break
multi_line = False
buf += chunk
print '< %s' % buf[:-1]
self.client.parse(buf[:-1])
class GUI(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.messages = Queue()
def run(self):
print 'Start reading input'
while True:
msg = sys.stdin.readline()
if not msg:
print 'ctrl-d'
sys.exit(-1)
break
msg = msg[:-1]
print msg
if msg == 'q':
print 'quitting'
sys.exit(-1)
break
def start(self, client):
self.client = client
threading.Thread.start(self)
if __name__ == '__main__':
client = Client()
client.connect('ow150.science.uva.nl', 16897)
client.receive()
#if __name__ == '__main__':
print 'Program started'
gui = GUI()
print 'GUI started'
client = Client('ow150.science.uva.nl', 16897)
gui.start(client)
gui.join()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment