Skip to main content

Instant Messaging, Threading and Sockets

So we were given an assignment for software today. It's going to be used to teach us promala and spin and good multi-threaded software practices. The overall goal is to make a simple GUI based multi-user instant messager system in C++.
I haven't used allot of concurrency before so I thought I would investigate by trying some stuff out in python. Also I haven't used sockets directly before - so wanted to have a look at them.

Firstly taking a read of the Socket Programming HOWTO guide - there is plenty of information there. And also handy is the Socket documentation for python.

For now I just want a echoing server that can service multiple clients at once.

So the server will be the difficult part - might as well dive in there!

Firstly creating a socket and echoing any data it recieves is pretty easy with this loop:

while True:
           data = self.conn.recv(1024)
           if not data:
               break
            self.conn.send(data)
Now wraping this up in a thread than can be started at any time is straighforward. And for good measure I'll add some logging in at the same time.

class AsyncEcho(threading.Thread):
    def __init__(self, conn, addr):
        threading.Thread.__init__(self)
        self.conn = conn
        self.addr = repr(addr) # Note just storing string for identification purposes

    def run(self):
        logging.info("Starting to run thread for client: %s" % self.addr)
        while True:
            logging.debug("server waiting to receive from client: %s" % self.addr)
            data = self.conn.recv(1024)
            if not data:
                logging.debug("Connection to client '%s' complete. Breaking connection" % self.addr)
                break
            logging.debug('Server received: "%s" from client "%s", sending back...' % (data,self.addr))
            self.conn.send(data)
        logging.info('Finished background servicing of client: %s' % self.addr)

 And the rest of the script that actually starts these threads, minus the imports:


logging.info("Server started")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.debug("Created a socket on the server")
s.bind((HOST, PORT))
logging.debug("Server Socket has been bound. Server is ready to accept connections")
while True:
    s.listen(5) # We want to queue up at most 5 requests
    logging.debug("Main thread of server listening for new connections")
    conn, addr = s.accept()
    
    logging.info('New connection by <%s>' %  repr(addr))
    logging.debug("Socket Object: %s" % repr(conn))
    background = AsyncEcho(conn, addr)
    logging.info("Created a new thread object to service this client, about to start it.")
    background.start()
    logging.info('Started the thread, the main program continues to run in foreground.')

 Now that wasn't too painful at all, the client is even easier. It needs to establish a connection via the socket with the server, then pass and receive data. Easy as:

clientName = raw_input("Client Name: ")

HOST = 'localhost'        # The remote host, could be differant to server...

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.debug("Created a socket on the client")
s.connect((HOST, PORT))
logging.debug("Client socket connected")

logging.debug("Sending Client name")
s.send(clientName)
logging.debug("Sent data, trying to receive now")
data = s.recv(1024)
logging.debug("Data received '%s'" % data)
Now we might as well have a loop for the client so it acts more like a command line:

logging.info("Start a loop. 'quit' will quit")
while True:
    data = raw_input(">")
    if data == "quit":
        break
    s.send(data)
    data2 = s.recv(1024)

    print(data2)



So starting up the server:


brian@brian-hitlab:~/projects/python/instantmess/src$ python server.py
INFO:root:Logger enabled
INFO:root:Server started
DEBUG:root:Created a socket on the server
DEBUG:root:Server Socket has been bound. Server is ready to accept connections
DEBUG:root:Main thread of server listening for new connections



At this point the server just waits for a client to be started, so lets do that in another terminal:

brian@brian-hitlab:~/projects/python/instantmess/src$ python client.py
INFO:root:Logger enabled
INFO:root:Client started
Client Name: client1
DEBUG:root:Created a socket on the client
DEBUG:root:Client socket connected
DEBUG:root:Sending Client name
DEBUG:root:Sent data, trying to receive now
DEBUG:root:Data received 'client1'

And then the loop:

INFO:root:Start a loop. 'quit' will quit
>Hi
Hi
>this is a test
this is a test
>sweet
sweet
>quit
DEBUG:root:Closing socket
Received 'quit'

During all this the server was spitting out lots as well:

DEBUG:root:server waiting to receive from client: ('127.0.0.1', 50535)
DEBUG:root:Server received: "Hi" from client "('127.0.0.1', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('127.0.0.1', 50535)
DEBUG:root:Server received: "this is a test" from client "('127.0.0.1', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('127.0.0.1', 50535)
DEBUG:root:Server received: "sweet" from client "('127.0.0.1', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('127.0.0.1', 50535)
DEBUG:root:Connection to client '('127.0.0.1', 50535)' complete. Breaking connection
INFO:root:Finished background servicing of client: ('127.0.0.1', 50535)


Okay time for lunch.

Popular posts from this blog

My setup for downloading & streaming movies and tv

I recently signed up for Netflix and am retiring my headless home media pc. This blog will have to serve as its obituary. The box spent about half of its life running FreeNAS, and half running Archlinux. I’ll briefly talk about my experience with FreeNAS, the migration, and then I’ll get to the robust setup I ended up with.

The machine itself cost around $1000 in 2014. Powered by an AMD A4-7300 3.8GHz cpu with 8GB of memory. A SilverStone DS380 case is both functional, quiet and looks great. The hard drives have been updated over the last two years until it had a full compliment of 6 WD Green 4TiB drives - all spinning bits of metal though.

Initially I had the BSD based FreeNAS operating system installed. I had a single hard drive in its own ZFS pool for TV and Movies, and a second ZFS pool comprised of 5 hard drives for documents and photos.

FreeNAS is straight forward to use and setup, provided you only want to do things supported out of the box or by plugins. Each plugin is install…

Matplotlib in Django

The official django tutorial is very good, it stops short of displaying
data with matplotlib - which could be very handy for dsp or automated
testing. This is an extension to the tutorial. So first you must do the
official tutorial!
Complete the tutorial (as of writing this up to part 4).

Adding an image to a view

To start with we will take a static image from the hard drive and
display it on the polls index page.
Usually if it really is a static image this would be managed by the
webserver eg apache. For introduction purposes we will get django to
serve the static image. To do this we first need to change the
template.



Change the template
At the moment poll_list.html probably looks something like this:


<h1>Django test app - Polls</h1> {% if object_list %} <ul> {% for object in object_list %} <li><a href="/polls/{{object.id}}">{{ object.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> …

Python and Gmail with IMAP

Today I had to automatically access my Gmail inbox from Python. I needed the ability to get an unread email count, the subjects of those unread emails and then download them. I found a Gmail.py library on sourceforge, but it actually opened the normal gmail webpage and site scraped the info. I wanted something much faster, luckily gmail can now be accessed with both pop and imap.

After a tiny amount of research I decided imap was the better albiet slightly more difficult protocol. Enabling imap in gmail is straight forward, it was under labs.

The address for gmail's imap server is:

imap.gmail.com:993

Python has a library module called imaplib, we will make heavy use of that to access our emails. I'm going to assume that we have already defined two globals - username and password. To connect and login to the gmail server and select the inbox we can do:

importimaplibimap_server=imaplib.IMAP4_SSL("imap.gmail.com",993)imap_server.login(username,password)imap_server.select(…