summaryrefslogtreecommitdiff
path: root/asciifarm/client/connection.py
blob: 4eb0ffe7c134f2362f8a110699b1619dc00f5457 (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

import socket

from asciifarm.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
        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)
            callback(data)
    
    def send(self, message):
        send(self.sock, bytes(message, 'utf-8'))