Package tlslite :: Module bufferedsocket
[hide private]
[frames] | no frames]

Source Code for Module tlslite.bufferedsocket

 1  # Copyright (c) 2016, Hubert Kario 
 2  # 
 3  # See the LICENSE file for legal information regarding use of this file. 
 4   
 5  """Wrapper around the socket.socket interface that provides buffering""" 
 6   
 7  from collections import deque 
 8   
 9   
10 -class BufferedSocket(object):
11 """ 12 Socket that will buffer reads and writes to a real socket object 13 14 When buffer_writes is enabled, writes won't be passed to the real socket 15 until flush() is called. 16 17 Not multithread safe. 18 19 @type buffer_writes: boolean 20 @ivar buffer_writes: whether to buffer data writes, False by default 21 """ 22
23 - def __init__(self, socket):
24 """Associate socket with the object""" 25 self.socket = socket 26 self._write_queue = deque() 27 self.buffer_writes = False
28
29 - def send(self, data):
30 """Send data to the socket""" 31 if self.buffer_writes: 32 self._write_queue.append(data) 33 return len(data) 34 return self.socket.send(data)
35
36 - def sendall(self, data):
37 """Send data to the socket""" 38 if self.buffer_writes: 39 self._write_queue.append(data) 40 return None 41 return self.socket.sendall(data)
42
43 - def flush(self):
44 """Send all buffered data""" 45 buf = bytearray() 46 for i in self._write_queue: 47 buf += i 48 self._write_queue.clear() 49 if buf: 50 self.socket.sendall(buf)
51
52 - def recv(self, bufsize):
53 """Receive data from socket (socket emulation)""" 54 return self.socket.recv(bufsize)
55
56 - def getsockname(self):
57 """Return the socket's own address (socket emulation).""" 58 return self.socket.getsockname()
59
60 - def getpeername(self):
61 """ 62 Return the remote address to which the socket is connected 63 64 (socket emulation) 65 """ 66 return self.socket.getpeername()
67
68 - def settimeout(self, value):
69 """Set a timeout on blocking socket operations (socket emulation).""" 70 return self.socket.settimeout(value)
71
72 - def gettimeout(self):
73 """ 74 Return the timeout associated with socket operations 75 76 (socket emulation) 77 """ 78 return self.socket.gettimeout()
79
80 - def setsockopt(self, level, optname, value):
81 """Set the value of the given socket option (socket emulation).""" 82 return self.socket.setsockopt(level, optname, value)
83
84 - def shutdown(self, how):
85 """Shutdown the underlying socket.""" 86 self.flush() 87 return self.socket.shutdown(how)
88
89 - def close(self):
90 """Close the underlying socket.""" 91 self.flush() 92 return self.socket.close()
93