aboutsummaryrefslogtreecommitdiffstats
path: root/src/ReceiveDictTcp.py
blob: 784afb64b99a439b928ad8f3ac1c530ac1fddc98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import socket
import threading
import json
from Queue import Queue
import sys

class ReceiveDictTcp(object):
    def __init__(self, host, port, verbose=False):
        self.host = host
        self.port = port
        self.verbose = verbose
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))
        self.queue = Queue()
        self.thread = threading.Thread(target = self.listen)

    def start(self):
        self.thread.start()

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            client.setblocking(1)
            if self.verbose: print("connecting to " + str(client) + " " + str(address))
            self.listenToClient(client,address)

    def listenToClient(self, client, address):
        size = 1024
        while True:
            if self.verbose: print("Try receiving")
            try:
                data = client.recv(size)
                if data:
                    # Set the response to echo back the recieved data
                    jresponse = data
                    response = json.loads(jresponse)
                    client.send(json.dumps(response))
                    self.queue.put(response)
                else:
                    raise Exception('disconnected')
            except Exception as e:
                print str(e)
                client.close()
                return False