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:
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):
        self.conn = conn
        self.addr = repr(addr) # Note just storing string for identification purposes

    def run(self):"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)
            logging.debug('Server received: "%s" from client "%s", sending back...' % (data,self.addr))
            self.conn.send(data)'Finished background servicing of client: %s' % self.addr)

 And the rest of the script that actually starts these threads, minus the imports:"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()'New connection by <%s>' %  repr(addr))
    logging.debug("Socket Object: %s" % repr(conn))
    background = AsyncEcho(conn, addr)"Created a new thread object to service this client, about to start it.")
    background.start()'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")
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:"Start a loop. 'quit' will quit")
while True:
    data = raw_input(">")
    if data == "quit":
    data2 = s.recv(1024)


So starting up the server:

brian@brian-hitlab:~/projects/python/instantmess/src$ python
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
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
>this is a test
this is a test
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: ('', 50535)
DEBUG:root:Server received: "Hi" from client "('', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('', 50535)
DEBUG:root:Server received: "this is a test" from client "('', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('', 50535)
DEBUG:root:Server received: "sweet" from client "('', 50535)", sending back...
DEBUG:root:server waiting to receive from client: ('', 50535)
DEBUG:root:Connection to client '('', 50535)' complete. Breaking connection
INFO:root:Finished background servicing of client: ('', 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…

Driveby contribution to Python Cryptography

While at PyConAU 2016 I attended the Monday sprints and spent some time looking at a proposed feature I hoped would soon be part of cryptography. As most readers of this blog will know, cryptography is a very respected project within the Python ecosystem and it was an interesting experience to see how such a prominent open source project handles contributions and reviews.

The feature in question is the Diffie-Hellman Key Exchange algorithm used in many cryptography applications. Diffie-Helman Key Exchange is a way of generating a shared secret between two parties where the secret can't be determined by an eavesdropper observing the communication. DHE is extremely common - it is one of the primary methods used to provide "perfect forward secrecy" every time you initiate a TLS connection to an HTTPS website. Mathematically it is extremely elegant and the inventors were the recipients of the 2015 Turing award.

I wanted to write about this particular contribution because man…

Python, Virtualenv and Docker

Unsurprisingly I use some very popular Scientific Python packages like Numpy, Scipy and Scikit Learn. These packages don't get on that well with virtualenv and pip as they take a lot of external dependencies to build. These dependencies can be optional libraries like libblas and libatlas which if present will make Numpy run faster, or required dependencies like a fortran compiler.

Back in the good old days you wouldn't pin all your dependency versions down and you'd end up with a precarious mix of apt-get installed and pip installed packages. Working with other developers, especially on different operating system update schedules could be a pain. It was time to update your project when it breaks because of a dependency upgraded by the operating system.

Does virtualenv fully solve this? No, not when you have hard requirements on the binaries that must be installed at a system level.

Docker being at a lower level gives you much more control without adding too much extra comp…