blob: f01e489428795799a14010033aaaf60c800b9c1d (
plain) (
blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
"""Contains tcp package object."""
import json
import zlib
class JSONPackageError(Exception):
"""Error raised by JSONPackage."""
pass
class JSONPackage(object):
"""Send/receive json by tcp connection.
Attribute:
content: Content of the package body.
"""
ENCODING = 'utf-8'
COMPRESS_LEVEL = 2
HEADER_LENGTH = 10
def __init__(self):
"""Constructor."""
self.content = None
def send_to(self, fd):
"""Sends a string to the tcp-connection.
Args:
fd: Socket fd.
"""
try:
string = json.dumps(self.content)
body = JSONPackage._create_body_from_string(string)
header = JSONPackage._create_header_from_body(body)
fd.send(header + body)
except TypeError as e:
raise JSONPackageError('json: %r' % e)
def recv_from(self, fd):
"""Receives a string from the tcp-connection.
Args:
fd: Socket fd.
"""
header = JSONPackage._recv_header_string(fd)
body = JSONPackage._recv_body_string(fd, header)
try:
self.content = json.loads(body)
except ValueError as e:
raise JSONPackageError('Cannot loads to the json object: %r' % e)
@staticmethod
def _create_body_from_string(string):
"""Creates package body from data string.
Args:
string: Data string.
Returns:
Package body.
"""
byte_string = string.encode(JSONPackage.ENCODING)
return zlib.compress(byte_string, JSONPackage.COMPRESS_LEVEL)
@staticmethod
def _create_header_from_body(body):
"""Creates package header from package body.
Args:
body: Package body.
Returns:
Package header.
"""
header_string = ('%%0%dd' % JSONPackage.HEADER_LENGTH) % len(body)
return header_string.encode(JSONPackage.ENCODING)
@staticmethod
def _recv_header_string(conn):
"""Receives package header from specified tcp connection.
Args:
conn: The specified tcp connection.
Returns:
Package header.
"""
try:
byte = conn.recv(JSONPackage.HEADER_LENGTH)
return byte.decode(JSONPackage.ENCODING)
except UnicodeError as e:
raise JSONPackageError('Cannot decode the header string: %r.' % e)
@staticmethod
def _recv_body_string(conn, header):
"""Receives package body from specified tcp connection and header.
Args:
conn: The specified tcp connection.
header: The package header.
Returns:
Package body.
"""
try:
body_length = int(header)
body = conn.recv(body_length)
body_byte = zlib.decompress(body)
return body_byte.decode(JSONPackage.ENCODING)
except UnicodeError as e:
raise JSONPackageError('Cannot decode the body string: %r.' % e)
except ValueError as e:
raise JSONPackageError('Cannot get the body_length: %r' % e)
except zlib.error as e:
raise JSONPackageError('Cannot decompress the body: %r.' % e)
|