2019-12-08 08:57:10 +01:00
|
|
|
# -*- coding: UTF-8 -*-
|
|
|
|
|
2019-12-08 18:10:09 +01:00
|
|
|
from .exceptions import ConnectionClosed
|
2019-12-08 08:57:10 +01:00
|
|
|
|
|
|
|
|
|
|
|
class SocketTransport:
|
|
|
|
|
|
|
|
def __init__(self, sock):
|
|
|
|
self.sock = sock
|
|
|
|
|
|
|
|
def write(self, data):
|
|
|
|
"""
|
|
|
|
Write given bytes to socket. Loop as long as every byte in
|
|
|
|
string is written unless exception is raised.
|
|
|
|
"""
|
|
|
|
self.sock.sendall(data)
|
|
|
|
|
|
|
|
def read(self, length):
|
|
|
|
"""
|
|
|
|
Read as many bytes from socket as specified in length.
|
|
|
|
Loop as long as every byte is read unless exception is raised.
|
|
|
|
"""
|
|
|
|
data = bytearray()
|
|
|
|
while len(data) != length:
|
|
|
|
data += self.sock.recv((length - len(data)))
|
|
|
|
if not data:
|
|
|
|
raise ConnectionClosed('Connection unexpectedly closed.')
|
|
|
|
return data
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self.sock.close()
|