Skip to content

Instantly share code, notes, and snippets.

@audax
Created January 26, 2016 14:44
Show Gist options
  • Save audax/ea0f31e746c1e0d15dd0 to your computer and use it in GitHub Desktop.
Save audax/ea0f31e746c1e0d15dd0 to your computer and use it in GitHub Desktop.
from tornado.ioloop import IOLoop
from tornado.tcpserver import TCPServer
from tornado import gen
from tornado.iostream import StreamClosedError
BUFFER = 4*1024
async def handler(stream):
await stream.read_until(b'VER 1 AUTH', max_bytes=10)
auth = await stream.read_until(b'CMD', max_bytes=40)
auth_string = auth.decode('ASCII')
auth_type, token, _ = auth_string.split()
assert auth_type == 'Token'
command = await stream.read_until(b'\n', max_bytes=120)
command_string = command.decode('ASCII')
cmd, arg = command_string.split()
if cmd == 'PUT':
stream.write(b'GRANTED PUT\n')
while True:
try:
content = await stream.read_bytes(BUFFER, partial=True)
except StreamClosedError:
break
await do_stuff(content)
stream.write(b'ACK\n')
else:
stream.write(b'invalid command received')
stream.close()
async def do_stuff(content):
print(repr(content))
class BlockServer(TCPServer):
@gen.coroutine
def handle_stream(self, stream, address):
print("handle stream")
yield handler(stream)
if __name__ == '__main__':
server = BlockServer()
server.bind(7777)
server.start(0) # Forks multiple sub-processes
IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment