summaryrefslogtreecommitdiff
path: root/metaserver/metastruct.py
blob: e187b65d24dc3d51144806a48f79fd5650dbc1be (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import sys, os
LOCALDIR = __file__
LOCALDIR = os.path.abspath(os.path.dirname(LOCALDIR))
sys.path.insert(0, os.path.dirname(LOCALDIR))

from common.msgstruct import *
from socket import error

MMSG_INFO     = 'I'
MMSG_START    = '+'
MMSG_STOP     = '-'
MMSG_LIST     = 'L'
MMSG_ROUTE    = 'R'
MMSG_TRACEBACK= 'T'
MMSG_UDP_ADDR = 'U'

RMSG_WAKEUP   = 'w'
RMSG_PING     = 'p'
RMSG_PONG     = 'o'
RMSG_SYNC     = 'y'
RMSG_CONNECT  = 'c'
RMSG_LIST     = 'l'
RMSG_UDP_ADDR = 'u'
RMSG_UDP_CONN = 'd'
RMSG_NO_HOST  = '?'


def encodedict(dict):
    data = []
    for key, value in list(dict.items()):
        data.append(message('#', key, value))
    return ''.join(data)

def encodelist(list):
    return message('[', *list)

def decodedict(buffer):
    result = {}
    while 1:
        msg, buffer = decodemessage(buffer)
        if msg is None or len(msg) < 3 or msg[0] != '#':
            break
        result[msg[1]] = msg[2]
    return result

def decodelist(buffer):
    msg, buffer = decodemessage(buffer)
    assert msg[0] == '['
    return list(msg[1:])


class MessageSocket:
    
    def __init__(self, s):
        self.s = s
        self.buffer = ""

    def receive(self):
        try:
            data = self.s.recv(2048)
        except error:
            data = ''
        if not data:
            self.disconnect()
            return
        self.buffer += data
        while 1:
            msg, self.buffer = decodemessage(self.buffer)
            if msg is None:
                break
            if msg[0] not in self.MESSAGES:
                print('unknown message %r' % (msg[0],), file=sys.stderr)
            else:
                fn = self.MESSAGES[msg[0]]
                fn(self, *msg[1:])