Created
May 25, 2020 14:10
-
-
Save calimaborges/f4255a3af9d178255a6c145175d2ad5e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import websocket | |
import _thread as thread | |
import time | |
class Database: | |
dados = [] | |
def add_dado(self, dado): | |
self.dados.append(dado) | |
def get_dados(self): | |
return self.dados | |
class WebsocketApi: | |
def __init__(self, database): | |
self.database = database | |
def on_message(self, message): | |
print("Message", message) | |
self.database.add_dado(message) | |
def on_error(self, error): | |
print("ERROR!", error) | |
def on_close(self): | |
print("CONEXÃO COM SOCKET FECHADA") | |
def on_open(self): | |
def run (*args): | |
dado_fake_atual = 0 | |
while True: | |
message = "dado_fake %i" % dado_fake_atual | |
self.ws.send(message) | |
dado_fake_atual = dado_fake_atual + 1 | |
time.sleep(1) | |
thread.start_new_thread(run, ()) | |
def start(self): | |
self.ws = websocket.WebSocketApp("ws://echo.websocket.org", on_message = self.on_message, on_error = self.on_error, on_close = self.on_close) | |
self.ws.on_open = self.on_open | |
if __name__ == "__main__": | |
websocket.enableTrace(True) | |
database = Database() | |
wsapi = WebsocketApi(database) | |
wsapi.start() | |
def run (*args): | |
while True: | |
print(database.get_dados()) | |
time.sleep(2) | |
thread.start_new_thread(run, ()) | |
wsapi.ws.run_forever() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment