Skip to content

Instantly share code, notes, and snippets.

@Sando1
Created November 15, 2018 08:04
Show Gist options
  • Save Sando1/d323398b3ae6304471f839bf87fc52cf to your computer and use it in GitHub Desktop.
Save Sando1/d323398b3ae6304471f839bf87fc52cf to your computer and use it in GitHub Desktop.
Assumes this class will be instantiated from the main loop upon incoming connections
import queue
import struct
import asyncio
import dill
import settings as s
import services as sr
CREATE, UPDATE, FS, FILE, QUIT, ERROR, SUCCESS, INVALID = range(8)
class CommandObject(object):
'''A command object to pass. It ensures security'''
def __init__(self, command, data=None):
self.command = command
self.data = data
class Connection():
'''
Description: Handle every client.
'''
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
self.msg_q = asyncio.Queue()
readTask = asyncio.create_task(self.read())
handleTask = asyncio.create_task(self.handle())
#writeTask = asyncio.create_task(self.write())
async def read(self):
try:
header = await self.reader.readexactly(4)
length = struct.unpack('!I', header)[0]
data = await self.reader.readexactly(length)
message = dill.loads(data)
print('received {} and {}'.format(message.command, message.data))
await self.msg_q.put(message)
except Exception as e:
print(e)
async def handle(self):
try:
command = await self.msg_q.get()
if command.command == CREATE: #create file
#sr.createFile(command.data['path'], command.data['file'])
print('message gotten')
pass
if command.command == UPDATE: #update file
sr.updateFile(command.data['path'], command.data['file'])
if command.command == FS: #file structure
#if asking for fs
if command.data == None:
data = dill.dumps(CommandObject(2, s.FILES))
header = struct.pack('!I', len(data))
self.writer.write(header + data)
#if replying with fs
else:
sr.updateFs(command.data)
if command.command == FILE: #file
if command.data == None:
print('message gotten')
else:
#someone has responded with a file
pass
if command.command == QUIT: #quit
print('message gotten')
pass
if command.command == ERROR: #error
print('message gotten')
return
if command.command == SUCCESS or command.command == INVALID: #success or invalid
#if an invalid result or success result is given, the server
#doesnt have to do anything.
print('message gotten')
pass
self.msg_q.task_done()
except Exception as e:
print(e)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment