dpallot / simple-websocket-server

A python based websocket server that is simple and easy to use.
950 stars 320 forks source link

I need a help #99

Open jorgebg2016 opened 4 years ago

jorgebg2016 commented 4 years ago

I would like to know whether is possible to call a function outside the server class handler. I have to emit datas from my Python modules for the Javascript events handler. Somebody can help me?

ccostel commented 4 years ago

Not sure I understand your question. But I think this example that I also stole from somewhere here :)

import threading
import time
import json
import logging
import websockets
from queue_helpers import deque

from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

USERS = set()

class SimpleEcho(WebSocket):
    def handleMessage(self):
        self.sendMessage(self.data)

    def handleConnected(self):
        USERS.add(self)

    def handleClose(self):
        USERS.remove(self)

server = SimpleWebSocketServer('', 8888, SimpleEcho)
# server = SimpleWebSocketServer('', 8888, SimpleEcho, selectInterval=0.1)

def push_out_news():
    while True:
        news_item = deque()
        if USERS and news_item:
            for user in USERS:
                user.sendMessage(str(news_item))
        time.sleep(0.2)

if __name__ == '__main__':
    t = threading.Thread(target=server.serveforever)
    t.setDaemon(True)
    t.start()
    push_out_news()