forked from Lawouach/WebSocket-for-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadedclient.py
More file actions
98 lines (77 loc) · 2.83 KB
/
Copy paththreadedclient.py
File metadata and controls
98 lines (77 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# -*- coding: utf-8 -*-
import threading
from ws4py.client import WebSocketBaseClient
__all__ = ['WebSocketClient']
class WebSocketClient(WebSocketBaseClient):
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None,
ssl_options=None, headers=None, exclude_headers=None):
"""
.. code-block:: python
from ws4py.client.threadedclient import WebSocketClient
class EchoClient(WebSocketClient):
def opened(self):
for i in range(0, 200, 25):
self.send("*" * i)
def closed(self, code, reason):
print(("Closed down", code, reason))
def received_message(self, m):
print("=> %d %s" % (len(m), str(m)))
try:
ws = EchoClient('ws://localhost:9000/echo', protocols=['http-only', 'chat'])
ws.connect()
except KeyboardInterrupt:
ws.close()
"""
WebSocketBaseClient.__init__(self, url, protocols, extensions, heartbeat_freq,
ssl_options, headers=headers, exclude_headers=exclude_headers)
self._th = threading.Thread(target=self.run, name='WebSocketClient')
self._th.daemon = True
@property
def daemon(self):
"""
`True` if the client's thread is set to be a daemon thread.
"""
return self._th.daemon
@daemon.setter
def daemon(self, flag):
"""
Set to `True` if the client's thread should be a daemon.
"""
self._th.daemon = flag
def run_forever(self):
"""
Simply blocks the thread until the
websocket has terminated.
"""
while not self.terminated:
self._th.join(timeout=0.1)
def handshake_ok(self):
"""
Called when the upgrade handshake has completed
successfully.
Starts the client's thread.
"""
self._th.start()
if __name__ == '__main__':
from ws4py.client.threadedclient import WebSocketClient
class EchoClient(WebSocketClient):
def opened(self):
def data_provider():
for i in range(0, 200, 25):
yield "#" * i
self.send(data_provider())
for i in range(0, 200, 25):
self.send("*" * i)
def closed(self, code, reason):
print(("Closed down", code, reason))
def received_message(self, m):
print("#%d" % len(m))
if len(m) == 175:
self.close(reason='bye bye')
try:
ws = EchoClient('ws://localhost:9000/ws', protocols=['http-only', 'chat'],
headers=[('X-Test', 'hello there')])
ws.connect()
ws.run_forever()
except KeyboardInterrupt:
ws.close()