source: code/session.py @ 133

Last change on this file since 133 was 23, checked in by trishank, 7 years ago

Add pre-release upPIR from June 2011.

File size: 2.3 KB
Line 
1# This module wraps communications in a signaling protocol.   The purpose is to
2# overlay a connection-based protocol with explicit message signaling.   
3#
4# The protocol is to send the size of the message followed by \n and then the
5# message itself.   The size of a message must be able to be stored in
6# sessionmaxdigits.   A size of -1 indicates that this side of the connection
7# should be considered closed.
8#
9# Note that the client will block while sending a message, and the receiver
10# will block while recieving a message.   
11#
12# While it should be possible to reuse the connectionbased socket for other
13# tasks so long as it does not overlap with the time periods when messages are
14# being sent, this is inadvisable.
15
16class SessionEOF(Exception):
17  pass
18
19# this limits the size of a message to 10**20.   Should be good enough
20sessionmaxdigits = 20
21
22# get the next message off of the socket...
23def recvmessage(socketobj):
24
25  messagesizestring = ''
26  # first, read the number of characters...
27  for junkcount in range(sessionmaxdigits):
28    currentbyte = socketobj.recv(1)
29
30    if currentbyte == '\n':
31      break
32   
33    # not a valid digit
34    if currentbyte not in '0123456789' and messagesizestring != '' and currentbyte != '-':
35      raise ValueError, "Bad message size"
36     
37    messagesizestring = messagesizestring + currentbyte
38
39  else:
40    # too large
41    raise ValueError, "Bad message size"
42
43  messagesize = int(messagesizestring)
44 
45  # nothing to read...
46  if messagesize == 0:
47    return ''
48
49  # end of messages
50  if messagesize == -1:
51    raise SessionEOF, "Connection Closed"
52
53  if messagesize < 0:
54    raise ValueError, "Bad message size"
55
56  data = ''
57  while len(data) < messagesize:
58    chunk =  socketobj.recv(messagesize-len(data))
59    if chunk == '':
60      raise SessionEOF, "Connection Closed"
61    data = data + chunk
62
63  return data
64
65# a private helper function
66def _sendhelper(socketobj,data):
67  sentlength = 0
68  # if I'm still missing some, continue to send (I could have used sendall
69  # instead but this isn't supported in repy currently)
70  while sentlength < len(data):
71    thissent = socketobj.send(data[sentlength:])
72    sentlength = sentlength + thissent
73
74
75
76# send the message
77def sendmessage(socketobj,data):
78  header = str(len(data)) + '\n'
79  _sendhelper(socketobj,header)
80
81  _sendhelper(socketobj,data)
82
83
84
Note: See TracBrowser for help on using the repository browser.