def __init__(self, name, msgHandler, server_ip, server_port):
        self.server = None
        self.name = name
        self.serverIp = server_ip
        self.serverPort = server_port
        self.msgHandler = msgHandler

        self.parser = MsgParser()
        self.thread = None
        self.run = True
        self.running = False
Beispiel #2
0
    def leave(self):
        if self.is_chairman:
            return

        if self.client:
            leaveMsg = MsgParser.buildLeaveMsg(self.my_name)
            self.client.sendMsg(leaveMsg)
        time.sleep(1)

        if self.server:
            redirectMsg = MsgParser.buildRedirectMsg(self.addr)
            self.server.sendMsg(redirectMsg)
        time.sleep(3)
Beispiel #3
0
 def broadcastMsg(self, msg):
     self.msgHandler(self.my_name + ' : ' + msg)
     msg = MsgParser.buildChatMsg(self.my_name, msg)
     if self.client:
         self.client.sendMsg(msg)
     if self.server:
         self.server.sendMsg(msg)
 def __init__(
         self,
         msg_handler=MessageHandler(),
         deserializer=Deserializer(),
         msg_parser=MsgParser(),
 ):
     # self._data_recv = b'',
     self._msg_handler = msg_handler  # ????????????
     self._desialiser = deserializer
     self._msg_parser_py = msg_parser
def test_parser(monkeypatch):

    url = "https://www.simple.com"

    def mockopen(browser, link):
        assert url == link
        return None
    monkeypatch.setattr(mechanize.Browser, "open", mockopen)

    title = "Simple | Online Banking With Automatic Budgeting & Savings"

    def mocktitle(browser):
        return title
    monkeypatch.setattr(mechanize.Browser, "title", mocktitle)

    parse = MsgParser()
    # hijack Browser instance so it can be mocked
    parse.browser = mechanize.Browser()
    parse.parse_message("I am @sam and here is a link: https://www.simple.com have a nice day (smiley).")
    expected = {"raw": "I am @sam and here is a link: https://www.simple.com have a nice day (smiley).", "mentions": ["sam"], "emoticons": ["smiley"], "links": [{"url": "https://www.simple.com", "title": "Simple | Online Banking With Automatic Budgeting & Savings"}]}
    assert json.dumps(expected) == parse.to_json_str()
Beispiel #6
0
 def _run(self):
     self.server.bind(('0.0.0.0', self.port))
     self.server.listen(self.port)
     while self.run:
         ready = select.select([self.server], [], [], 1)
         if not ready[0]:
             continue
         conn, addr = self.server.accept()
         self.connections[conn] = {'addr': addr, 'parser': MsgParser()}
         print(addr, " connected")
         thread = threading.Thread(target=self.clientThread, args=(conn, ))
         thread.start()
Beispiel #7
0
 def redirect(self, addr, name, newAddr):
     # print(addr, self.connections)
     for conn, info in self.connections.items():
         if info['addr'] == addr:
             msg = MsgParser.buildRedirectMsg(newAddr)
             conn.send(msg.encode())
class ChattingClient:
    def __init__(self, name, msgHandler, server_ip, server_port):
        self.server = None
        self.name = name
        self.serverIp = server_ip
        self.serverPort = server_port
        self.msgHandler = msgHandler

        self.parser = MsgParser()
        self.thread = None
        self.run = True
        self.running = False

    def setServer(self, ip, port):
        self.serverIp = ip
        self.serverPort = port

    def connectServer(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((self.serverIp, self.serverPort))
        self.server = server

        joinMsg = self.parser.buildJoinMsg(self.name)
        self.sendMsg(joinMsg)

    def start(self):
        print('Starting client!')
        self.connectServer()
        self.thread = threading.Thread(target=self._start)
        self.thread.start()

    def _start(self):
        self.running = True
        while self.run:
            sockets_list = [self.server]
            read_sockets, write_socket, error_socket = select.select(
                sockets_list, [], [], 1)

            if not read_sockets:
                continue
            message = read_sockets[0].recv(2048)
            msg = self.parser.parse(message)
            if msg:
                #print('Client received msg:', msg)
                self.onRcvdMsg(msg)

        print('client stopping!')
        self.server.close()
        self.running = False

    def stop(self):
        self.run = False

    def isRunning(self):
        return self.running

    def sendMsg(self, msg):
        msg = json.dumps(msg)
        self.server.send(msg.encode())

    def onRcvdMsg(self, msg):
        if msg['type'] == 'chat':
            self.msgHandler.sendToUnderlayer(msg)
        else:
            self.msgHandler.onCtrlMsg(msg, self.server)
        msg = json.dumps(msg)
        self.server.send(msg.encode())

    def onRcvdMsg(self, msg):
        if msg['type'] == 'chat':
            self.msgHandler.sendToUnderlayer(msg)
        else:
            self.msgHandler.onCtrlMsg(msg, self.server)


class TestMsgHandler:
    def sendToUnderlayer(self, msg):
        print('sendToUnderlayer:', msg)

    def onCtrlMsg(self, msg, connection):
        pass


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Correct usage: script, IP address, port number, name")
        exit()
    IP_address = str(sys.argv[1])
    Port = int(sys.argv[2])
    name = str(sys.argv[3])
    client = ChattingClient(name, TestMsgHandler, IP_address, Port)
    client.start()
    msg = MsgParser.buildChatMsg(name, 'Hello, Alice!')
    client.sendMsg(msg)
    time.sleep(200)
    client.stop()