Exemple #1
0
    def run(self):
        # TODO: Make MessageReceiver receive and handle payloads
        parser = MessageParser()

        while True:
            package = self.connection.recv(4096)
            if package:
                parser.parse(package)
Exemple #2
0
    def run(self):
        # TODO: Make MessageReceiver receive and handle payloads
        parser = MessageParser()

        while True:
            package = self.connection.recv(4096)
            if package:
                parser.parse(package)
Exemple #3
0
class ClientHandler(socketserver.BaseRequestHandler):
    """
    This is the ClientHandler class. Everytime a new client connects to the
    server, a new ClientHandler object will be created. This class represents
    only connected clients, and not the server itself. If you want to write
    logic for the server, you must write it outside this class
    """
    def handle(self):
        """
        This method handles the connection between a client and the server.
        """
        self.ip = self.client_address[0]
        self.port = self.client_address[1]
        self.connection = self.request

        # Init
        self.messageEncoder = MessageEncoder()
        self.messageParser = MessageParser()

        # Loop that listens for messages from the client
        while True:
            received_string = self.connection.recv(4096).decode()

            if received_string == "":
                self.connection.close()
                del connected_clients[self.connection]
                break
            else:
                payload = self.messageParser.parse(received_string)
                if 'login' in payload.keys():
                    if re.match("^[A-Za-z0-9_-]*$", payload['login']):
                        self.connection.send(
                            self.messageEncoder.encode_history(
                                history).encode())
                        connected_clients[self.connection] = payload['login']
                    else:
                        self.connection.send(
                            self.messageEncoder.encode_error(
                                "Invalid username").encode())
                elif 'logout' in payload.keys():
                    self.connection.close()
                    del connected_clients[self.connection]
                    return
                elif 'message' in payload.keys():
                    message = self.messageEncoder.encode_message(
                        connected_clients[self.connection], payload['message'])
                    history.append(message)
                    for conn in connected_clients.keys():
                        conn.send(message.encode())
                elif 'names' in payload.keys():
                    self.connection.send(
                        self.messageEncoder.encode_info(', '.join(
                            connected_clients.values())).encode())
                elif 'help' in payload.keys():
                    self.connection.send(
                        self.messageEncoder.encode_info(
                            "This is the help").encode())
Exemple #4
0
 def update(self):
     #check for messages from server
     try:
         data = self.sock.recv(512) #TODO: change to server's max possible message length
         if data:
             while not data.endswith(';'):
                 data += self.sock.recv(1)
             messages = [m for m in data.split(';') if m != '']
             for m in messages:
                 MessageParser.parse(m)
                 #print 'Message from server: ' + m #TODO: delete this when all parsing functions are implemented
         else:
             Shared.main_window.calls.put((Shared.main_window.destroy,))
             print 'Server Disconnected'
     except socket.error:
         #since the socket is non-blocking, it will raise an error each time it doesn't receive any data
         pass
     
     #check outgoing messages queue
     while not self.outgoing_messages.empty():
         msg = self.outgoing_messages.get()
         self.sock.send(msg)
         print 'Sent message to server: ' + msg
Exemple #5
0
def server_thread():
    global users_sockets, should_exit
    while not should_exit:
        for username in users_sockets.keys():
            #check the active socket for data
            try:
                data = users_sockets[username].main_socket.recv(512)
                if data:
                    while not data.endswith(';'):
                        data += users_sockets[username].main_socket.recv(1)
                    messages = [m for m in data.split(';') if m != '']
                    for msg in messages:
                        print 'got message from user '+ username+ ' : '+ msg
                        MessageParser.parse(msg, username)
                else:
                    print username + "'s main socket disconnected"
                    MessageParser.parse_user_state_changed(0, username)
                    users_sockets[username].close()
                    users_sockets.pop(username, None)
                    continue
            except socket.error: pass
            
            #check all the sleeping sockets for disconnection
            if any(users_sockets[username].sleeping_sockets):
                ready_to_read, wr, er = select.select(users_sockets[username].sleeping_sockets, [], [], 0)
                for sock in ready_to_read:
                    try:
                        if not sock.recv(2):
                            print 'a sleeping socket from ' + username + ' had disconnected'
                            sock.close()
                            users_sockets[username].remove(sock)
                    except socket.error: pass
                
                
        time.sleep(1.0/60.0)
    print 'server thread ended'    
Exemple #6
0
class MessageReceiver(object):
    def __init__(self, sock):
        self.sock = sock
        self.parser = MessageParser()

    def receive(self):
        try:
            data = self.sock.recv(2048)
            #TODO make sure completely received data from client
            if data:
                message = self.parser.parse(data)
                return message
            return None
        except:
            traceback.print_exc()
            return None
Exemple #7
0
class MessageReceiver(object):
    def __init__(self, sock):
        self.sock = sock
        self.parser = MessageParser()

    def receive(self):
	try: 
        	data = self.sock.recv(2048)
        	#TODO make sure completely received data from client
        	if data:
            		message = self.parser.parse(data)
            		return message
        	return None
	except:
		traceback.print_exc()
		return None
def formResponse(sender_id, text):
    msg_type = MessageParser.parse(text)
    responseList = []
    if msg_type == MessageParser.GREETING_MSG:
        message1 = '''Hello, Welcome to IPO Notifier.'''
        message2 = '''You can use following Keywords to get IPO details.
- Upcoming IPO
- Today's IPO, Current IPO
- Recent IPO
- Help.'''
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)
        jsonFormat = generateJSONResposneForText(message2)
        responseList.append(jsonFormat)

        if not DBHelper.isSubscribed(sender_id):
            jsonFormat = generateJSONResposneForPostbackButtons(
                '''Do you want to Get Notified when new IPO is going to be listed on BSE or NSE?''',
                'Yes, Subscribe Me', 'Subscribe', "No, Don't Notify Me",
                'Unsubscribe')
            responseList.append(jsonFormat)

    elif msg_type == MessageParser.UNKNOWN_MSG:
        message1 = "I didn't understand that. Try typing Help :P ."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)

    elif msg_type == MessageParser.HELP:
        message1 = '''Use Following Keywords for your task.
- Upcoming IPO
- Current IPO
- Recent IPO
- ipo 'Company name'.'''
        message2 = "To get latest IPO update notifications type 'Subscribe'."
        if DBHelper.isSubscribed(sender_id):
            message2 = "To unsubscribe from getting IPO update notifications type 'Unsubscribe'."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)
        jsonFormat = generateJSONResposneForText(message2)
        responseList.append(jsonFormat)

    elif msg_type == MessageParser.UPCOMING_IPO:
        ipolist = IPOHelper.getUpcomingIPO()
        for ipoData in ipolist:
            jsonFormat = generateJSONResposneForIPO(ipoData)
            responseList.append(jsonFormat)

    elif msg_type == MessageParser.ALL_IPO:
        ipolist = IPOHelper.getLast6IPO()
        for ipoData in ipolist:
            jsonFormat = generateJSONResposneForIPO(ipoData)
            responseList.append(jsonFormat)

    elif msg_type == MessageParser.IPO_NAME:
        ipoName = MessageParser.parseIPOName(text)
        ipolist = IPOHelper.getIPObyName(ipoName)
        if not ipoName:
            ipolist = IPOHelper.getRunningIPO(False)
            msg1 = "Try ipo 'company name'."
            msg2 = "By the way here is the running IPO List"
            jsonFormat = generateJSONResposneForText(msg1)
            responseList.append(jsonFormat)
            if ipolist:
                jsonFormat = generateJSONResposneForText(msg2)
                responseList.append(jsonFormat)

        for ipoData in ipolist:
            jsonFormat = generateJSONResposneForIPO(ipoData)
            responseList.append(jsonFormat)

    #gives list of running ipo
    elif msg_type == MessageParser.TODAYS_IPO:
        ipolist = IPOHelper.getRunningIPO(False)
        for ipoData in ipolist:
            jsonFormat = generateJSONResposneForIPO(ipoData)
            responseList.append(jsonFormat)

    elif msg_type == MessageParser.UNSUBSCRIBE:
        DBHelper.updateuser(sender_id, '0')
        message1 = "We're sad to see you go. You can type 'Subscribe' any time if you want to get updates again."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)

    elif msg_type == MessageParser.SUBSCRIBE:
        DBHelper.updateuser(sender_id, '1')
        message1 = "You are successfully subscribed. We will notify you for latest IPO news and updates."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)

    elif msg_type == MessageParser.THANKS:
        DBHelper.updateuser(sender_id, '1')
        message1 = "Always happy to serve."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)

    if not responseList:
        message1 = "Sorry, No Results Found."
        jsonFormat = generateJSONResposneForText(message1)
        responseList.append(jsonFormat)

    return responseList