summaryrefslogtreecommitdiff
path: root/asciifarmclient/connection.py
blob: 707a02ef56a2241eed5c7a76eb848e6acfbd50f3 (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

import socket

from asciifarmclient.common.tcommunicate import send, receive
from asciifarmclient.common import messages
import json

class Connection:
    
    def __init__(self, socketType):
        if socketType == "abstract" or socketType == "unix":
            sockType = socket.AF_UNIX
        elif socketType == "inet":
            sockType = socket.AF_INET
        else:
            raise ValueError("Invalid socket type: %r" % (socketType,))
        self.sock = socket.socket(sockType, socket.SOCK_STREAM)
    
    def connect(self, address):
        self.sock.connect(address)
    
    def receive(self):
        databytes = receive(self.sock)
        if len(databytes) == 0:
            return None
        datastr = databytes.decode('utf-8')
        msg = json.loads(datastr)
        message = messages.message_from_json(msg)
        return message
    
    def listen(self, callback, onError):
        while True:
            try:
                message = self.receive()
            except Exception as err:
                onError(err)
            else:
                callback(message)
    
    def send(self, message):
        send(self.sock, message.to_json_bytes())