Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created July 24, 2012 18:28
Show Gist options
  • Select an option

  • Save kurtbrose/3171673 to your computer and use it in GitHub Desktop.

Select an option

Save kurtbrose/3171673 to your computer and use it in GitHub Desktop.
Class to make socket behave like string
'''
Small class to make a socket behave like a string.
The idea is to be able to pass an string-like thing to a parser that doesn't know in advance how much data it will require.
This requires a lot of copying; reading data is O(n**2). It is probably better to make a parser which works off of a stream.
If the data is available as a string, but the parser works with a stream, StringIO is well behaved.
'''
class SocketString(object):
def __init__(self, sock):
self.sock = sock
self.buff = ""
def __getitem__(self, key):
if type(key) is slice:
self._buffer_to(key.stop)
else:
self._buffer_to(key)
return self.buff[key]
def _buffer_to(self, offset):
more = []
len_more = 0
while len(self.buff) + len_more < offset:
nxt = self.sock.recv(4096)
len_more += len(nxt)
more.append(nxt)
self.buff = ''.join([self.buff]+more)
'''
>>> import socket
>>> import strsock
>>> s = socket.create_connection(('google.com', 80))
>>> s.send('fdafdsafdsa\r\n\r\n')
15
>>> strsock = sockstr.SocketString(s)
>>> strsock[:3]
'HTT'
>>> strsock[:10]
'HTTP/1.1 4'
>>> strsock[:16]
'HTTP/1.1 400 Bad'
>>> strsock[2]
'T'
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment