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

import socket

from asciifarmclient.common.tcommunicate import send, receive

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 listen(self, callback, onError):
        while True:
            try:
                data = receive(self.sock)
            except Exception as err:
                onError(err)
            else:
                callback(data)
    
    def send(self, message):
        send(self.sock, message)