import json
import threading
import socket
import SocketServer

from orderbook import asks, bids


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        try:
            while True:
                data = self.request.recv(1024)
                response = ''

                if data:
                    handled_data, data_type = handle_data(data)
                    if handled_data:
                        response = handled_data

                self.request.sendall(response)

                if data:
                    break

        except socket.error:
            # Surpress errno 13 Broken Pipe
            pass


class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass


def create_server(host="localhost", port=0):
    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    return server


def handle_data(data):
    try:
        data = json.loads(data)
        if data['type'] == 'ask':
            return handle_ask(data), 'ask'
        elif data['type'] == 'bid':
            return handle_bid(data), 'bid'
        elif data['type'] == 'greeting':
            return handle_greeting(data), 'greeting'
    except ValueError, e:
        print e.message
        return e.message


def handle_ask(ask):
    asks.append(ask)


def handle_bid(bid):
    bids.append(bid)


def handle_greeting(greeting):
    return 'Hi!'

@@ -89,16 +89,36 @@
 ks, bids
+, match_incoming_ask
 %0A%0A%0Aclass
@@ -1137,36 +1137,45 @@
 :%0A            re
-turn
+sponse_dict =
  handle_ask(data
@@ -1179,15 +1179,8 @@
 ata)
-, 'ask'
 %0A   
@@ -1218,36 +1218,45 @@
 :%0A            re
-turn
+sponse_dict =
  handle_bid(data
@@ -1260,15 +1260,8 @@
 ata)
-, 'bid'
 %0A   
@@ -1312,20 +1312,29 @@
       re
-turn
+sponse_dict =
  handle_
@@ -1351,20 +1351,63 @@
 ata)
-, 'greeting'
+%0A        return json.dumps(response_dict), data%5B'type'%5D
 %0A   
@@ -1509,24 +1509,144 @@
     
-asks.append(ask)
+bid = match_incoming_ask(ask)%0A    if bid:%0A        return bid%0A    else:%0A        asks.append(ask)%0A        return 'Your ask got processed!'
 %0A%0A%0Ad

Reimplement very basic ask handling.