0

I want my websocket client to close connection as soon as my_flag is set to True. Here's my socket class:

class BridgeSocket(WebSocketClientProtocol):
    def __init__(self,factory,my_flag):
        self.my_flag = my_flag

Now, my_flag is set as true after some time somewhere else in the program run.(inside a different thread). Instead of waiting in a

while True:
    sleep(1)

kind of loop, is there any event which I can define and attach to my websocket class. i.e. a function which gets fired when my_flag is set to true

crazydiv
  • 812
  • 9
  • 30

2 Answers2

0

Use threading.Event.

# initialization code
self.my_event = threading.Event()

# sct.my_event.set() is called from somewhere

# waiting code, to replace while True:...
sct.my_event.wait()
shx2
  • 61,779
  • 13
  • 130
  • 153
  • I am not able to understand your solution. My class is deriving from WebSocketClientProtocol. How will I use threading events in that? Could you please explain in detail.Thanks – crazydiv Jan 02 '14 at 07:43
0

You should spawn your background task using Twisted deferToThread and then notify the WebSocket stuff running on the main thread using callFromThread.

oberstet
  • 21,353
  • 10
  • 64
  • 97