Page 1 of 1

Threaded websockets

Posted: Mon Sep 26, 2022 4:16 pm
by pepe
I'm trying to make a plugin that makes a websocket connection with a server. The problem: the websocket connection doesn't work if its executed within a thread, but the interesting thing is that when i unload the plugin it kinda connects to the server but that is useless since the plugin is shut down. Im using this library: https://pypi.org/project/websockets/

Code: Select all

from messages import SayText2
import enum
import threading
import websocket
from listeners.tick import GameThread


def on_ws_open(ws):
    print('socket connected')
    ws.send("Hello")


def on_ws_close(ws, close_status_code, close_msg):
    print(f'Socket closed: {close_msg}\n Status code: {close_status_code}')


def on_ws_message(ws, message):
    print(message)


def on_ws_error(ws, error):
    print('Socket error')
    # ws.send("Hello, server")


def start_ws():
    ws = websocket.WebSocketApp(
        url="ws://192.168.0.11:1337/ws",
        on_close=on_ws_close,
        on_message=on_ws_message,
        on_error=on_ws_error,
        on_open=on_ws_open
    )
    print("WebsocketApp created")
    ws_run = ws.run_forever(
        ping_interval=5
    )
    print("after ws_run")


def load():
    thread = GameThread(target=start_ws)
    thread.daemon = True
    thread.start()


def unload():
    pass

Image
Sorry if something is messed up, i have little experience with python and threading

Re: Threaded websockets

Posted: Mon Sep 26, 2022 7:16 pm
by pepe
I managed to fix it, i just added this to the server.cfg:

Code: Select all

sv_hibernate_when_empty 0

Turns out that the server messes with the created threads when the server is hibernating :wink:

Re: Threaded websockets

Posted: Mon Oct 17, 2022 10:59 am
by Jackson25
pepe wrote:I managed to fix it, i just added this to the server.cfg:

Code: Select all

sv_hibernate_when_empty 0

Turns out that the server messes with the created threads when the server is hibernating :wink:


Hello,

Thank you for the little tip, it helped me a lot.