Skip to content

Commit

Permalink
removed semicolons and added comments
Browse files Browse the repository at this point in the history
  • Loading branch information
snoato committed Dec 9, 2015
1 parent f520a4f commit 18541d0
Show file tree
Hide file tree
Showing 11 changed files with 283 additions and 241 deletions.
81 changes: 44 additions & 37 deletions lib/Client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,87 +5,94 @@

import NetworkUtil as NU
from Connectable import Connectable
from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer;
from Logger import Logger;
from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer
from Logger import Logger

#Class for storing client information and handle specific operations
class Client(Connectable):
controllable = True;
midac = None;
connectingId = None;
controllable = True
midac = None
connectingId = None
conf = None
LAO = None;
isWebsocket = False;
log = None;
LAO = None
isWebsocket = False
log = None

def __init__(self, socket, size, address, port, connectingId, conf, LAO, log):
self.socket = socket;
self.messageSize = size;
self.midac = MIDaCSerializer();
self.address = address;
self.port = port;
self.connectingId = connectingId;
self.conf = conf;
self.LAO = LAO;
self.log = log;
self.socket = socket
self.messageSize = size
self.midac = MIDaCSerializer()
self.address = address
self.port = port
self.connectingId = connectingId
self.conf = conf
self.LAO = LAO
self.log = log

#receives message and performs
def receiveAndDecode(self):
try:
if self.isWebsocket:
return NU.decode(self.socket.recv(self.messageSize));
return NU.decode(self.socket.recv(self.messageSize))
else:
return self.socket.recv(self.messageSize).decode("utf-8");
return self.socket.recv(self.messageSize).decode("utf-8")
except socket.error:
self.log.logAndPrintError("Connection reset by peer, if reocurring restart server");
self.log.logAndPrintError("Connection reset by peer, if reocurring restart server")
return False

#performs utf-8 encoding on msg and sends it or uses the webscoket send function
def sendAndEncode(self, msg):
if self.isWebsocket :
NU.sendData(self.socket, msg)
else:
self.socket.send(msg.encode("utf-8"));
self.socket.send(msg.encode("utf-8"))

#perform handshake
def performHandshake(self):
if not self.established:
#receive connreq or perform websocket handshake if client is connecting over websockets
if self.handshakeStatus == 0:
inputMSG = self.receiveAndDecode();
inputMSG = self.receiveAndDecode()
if not inputMSG:
self.socket.close()

if inputMSG[:3] == "GET":
handshake = NU.create_handshake(inputMSG)
self.sendAndEncode(handshake)
self.isWebsocket = True;
self.isWebsocket = True
else:
try:
msg = json.loads(inputMSG);
msg = json.loads(inputMSG)

if self.midac.GetMessageType(msg) == MSGType.ConnREQ:
self.handshakeStatus = 1;
self.handshakeStatus = 1
except ValueError:
self.log.logAndPrintError("Error while parsing input");
self.log.logAndPrintError("Error while parsing input")

#send connack to client
elif self.handshakeStatus == 1:
self.sendAndEncode(self.midac.GenerateConnACK("None", self.conf.SEGMENT_SIZE));
self.handshakeStatus = 2;
self.sendAndEncode(self.midac.GenerateConnACK("None", self.conf.SEGMENT_SIZE))
self.handshakeStatus = 2

#send connlao to client
elif self.handshakeStatus == 2:
#Creating test MIDaC Conn LAO here
self.sendAndEncode(self.LAO);
self.handshakeStatus = 3;
self.sendAndEncode(self.LAO)
self.handshakeStatus = 3

#receive connstt and set status to established
else:
inputMSG = self.receiveAndDecode();
inputMSG = self.receiveAndDecode()
if not inputMSG:
self.socket.close();
self.socket.close()
try:
msg = json.loads(inputMSG);
msg = json.loads(inputMSG)
if self.midac.GetMessageType(msg) == MSGType.ConnSTT:
self.established = True;
self.established = True
except ValueError:
self.established = False;
self.established = False

else:
raise Exception("Handshake already performed");
raise Exception("Handshake already performed")



114 changes: 60 additions & 54 deletions lib/ClientManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,120 +6,126 @@
import NetworkUtil as NU
from Client import Client
from ConfigHandler import ConfigHandler
from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer;
from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer

#Class for managing all connected clients
class ClientManager():
clients = None;
inputready = None;
outputready = None;
server = None;
newConnectedId = 0;
clients = None
inputready = None
outputready = None
server = None
newConnectedId = 0

log = None;
conf = None;
LAO = None;
log = None
conf = None
LAO = None

def __init__(self, server, log, conf, LAO):
self.clients = [];
self.inputready = [];
self.outputready = [];
self.server = server;
self.log = log;
self.conf = conf;
self.LAO = LAO;
self.clients = []
self.inputready = []
self.outputready = []
self.server = server
self.log = log
self.conf = conf
self.LAO = LAO

#Gets the socket descriptors of the clients, including an optional added socket descriptor
def getClientsSockets(self, added):
sockets = added;
sockets = added
for client in self.clients:
sockets.append(client.socket);
return sockets;
sockets.append(client.socket)
return sockets

#get the stored client object that has the given socket descriptor
def getClientBySocket(self, socket):
reqClient = None;
reqClient = None
for client in self.clients:
if client.socket == socket:
reqClient = client;
reqClient = client

return reqClient;
return reqClient

#get the handshaking clients
def getHandshakeSockets(self):
handshaking = [];
handshaking = []
for client in self.clients:
if not client.established:
handshaking.append(client);
return handshaking;
handshaking.append(client)
return handshaking

#performs select on all connected clients
def update(self):
self.inputready, self.outputready, excepts = select.select(self.getClientsSockets([self.server]), self.getClientsSockets([]), []);
self.inputready, self.outputready, excepts = select.select(self.getClientsSockets([self.server]), self.getClientsSockets([]), [])

#creates client object and adds it to client list. performed when client connected
def handleConnect(self):
client, address = self.server.accept();
client.setblocking(0);
client, address = self.server.accept()
client.setblocking(0)

self.clients.append(Client(client, self.conf.SEGMENT_SIZE, address[0], address[1], self.newConnectedId, self.conf, self.LAO, self.log));
self.clients.append(Client(client, self.conf.SEGMENT_SIZE, address[0], address[1], self.newConnectedId, self.conf, self.LAO, self.log))

self.log.logAndPrintMessage("Client "+`self.newConnectedId`+" ("+address[0]+":"+`address[1]`+") connected");
self.newConnectedId+=1;
self.log.logAndPrintMessage("Client "+`self.newConnectedId`+" ("+address[0]+":"+`address[1]`+") connected")
self.newConnectedId+=1

#calls handshake handling function on every connected client that is in handshake mode
def handleHandshake(self):
for client in self.getHandshakeSockets():
if (client.socket in self.inputready and (client.handshakeStatus == 0 or client.handshakeStatus == 3 )) or (client.socket in self.outputready and (client.handshakeStatus == 1 or client.handshakeStatus == 2)):
#try:
client.performHandshake();
client.performHandshake()
if client.established:
self.log.logAndPrintSuccess("Handshake with Client "+`client.connectingId`+" successful!");
self.log.logAndPrintSuccess("Handshake with Client "+`client.connectingId`+" successful!")
#except TypeError:
# self.clients.remove(client)
# self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!");
# self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!")
if client.socket in self.inputready:
self.inputready.remove(client.socket);
self.inputready.remove(client.socket)
if client.socket in self.outputready:
self.outputready.remove(client.socket);
self.outputready.remove(client.socket)

#handles input from clients (also used for disconnect)
def handleInput(self):
control = None;
control = None
for sock in self.inputready:
if sock == self.server:
self.handleConnect();
self.handleConnect()
else:
try:
client = self.getClientBySocket(sock);
client = self.getClientBySocket(sock)
if client.isWebsocket:
data = client.receiveAndDecode();
data = client.receiveAndDecode()
else:
data = NU.multiReceive(sock, self.conf.SEGMENT_SIZE);
data = NU.multiReceive(sock, self.conf.SEGMENT_SIZE)
if data:
#Only the longest lasting connected can send
if self.clients.index(self.getClientBySocket(sock)) == 0:
try:
control = json.dumps(data);
control = json.dumps(data)
except:
self.log.logAndPrintWarning("Unparseable client input");
self.log.logAndPrintWarning("Unparseable client input")
else:
if(sock in self.inputready):
self.inputready.remove(sock);
self.inputready.remove(sock)
if(sock in self.outputready):
self.outputready.remove(sock);
client = self.getClientBySocket(sock);
self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!");
self.clients.remove(client);
self.outputready.remove(sock)
client = self.getClientBySocket(sock)
self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!")
self.clients.remove(client)
except socket.error:
self.log.logAndPrintWarning("Socket Error");
return control;

self.log.logAndPrintWarning("Socket Error")
return control

#sends output to connected clients
def handleOutput(self, msg):
for sock in self.outputready:
try:
client = self.getClientBySocket(sock);
client = self.getClientBySocket(sock)
if client.isWebsocket:
client.sendAndEncode(msg)
else:
sock.send(msg);
sock.send(msg)
except socket.error:
self.log.logAndPrintError("Broken pipe warning, if reocurring restart server");
self.log.logAndPrintError("Broken pipe warning, if reocurring restart server")



Expand Down
Loading

0 comments on commit 18541d0

Please sign in to comment.