## 客户端
ws4py带有各种客户端实现。
#### 内置的客户端
内置的客户端只依赖于Python stdlib提供的模块。 客户端的内部循环在一个线程内运行,因此保持线程活动,直到Websocket关闭。
```
from ws4py.client.threadedclient import WebSocketClient
class DummyClient(WebSocketClient):
def opened(self):
def data_provider():
for i in range(1, 200, 25):
yield "#" * i
self.send(data_provider())
for i in range(0, 200, 25):
print i
self.send("*" * i)
def closed(self, code, reason=None):
print "Closed down", code, reason
def received_message(self, m):
print m
if len(m) == 175:
self.close(reason='Bye bye')
if __name__ == '__main__':
try:
ws = DummyClient('ws://localhost:9000/', protocols=['http-only', 'chat'])
ws.connect()
ws.run_forever()
except KeyboardInterrupt:
ws.close()
```
在这段代码中,当握手成功时,会调用opens()方法,在此方法中,我们向服务器发送一些消息。 首先,我们演示如何使用生成器来执行此操作,然后我们简单地发送字符串。
假设服务器收到消息时,receive_message(message)方法将打印服务器返回的消息,只要收到上一次发送的消息(长度为175)就关闭连接。
最后,使用服务器给出的代码和原因调用closed(code,reason = None)方法。
#### tornado
如果您正在使用tornado后端,则可以使用ws4py提供的Tornado客户端,如下所示:
```
from ws4py.client.tornadoclient import TornadoWebSocketClient
from tornado import ioloop
class MyClient(TornadoWebSocketClient):
def opened(self):
for i in range(0, 200, 25):
self.send("*" * i)
def received_message(self, m):
print m
if len(m) == 175:
self.close(reason='Bye bye')
def closed(self, code, reason=None):
ioloop.IOLoop.instance().stop()
ws = MyClient('ws://localhost:9000/echo', protocols=['http-only', 'chat'])
ws.connect()
ioloop.IOLoop.instance().start()
```
#### gevent
如果您正在使用gevent后端,则可以使用ws4py提供的gevent客户端,如下所示:
```from ws4py.client.geventclient import WebSocketClient```
这个客户是从从gevent的概念中受益的,如下所示:
```
ws = WebSocketClient('ws://localhost:9000/echo', protocols=['http-only', 'chat'])
ws.connect()
def incoming():
"""
Greenlet waiting for incoming messages
until ``None`` is received, indicating we can
leave the loop.
"""
while True:
m = ws.receive()
if m is not None:
print str(m)
else:
break
def send_a_bunch():
for i in range(0, 40, 5):
ws.send("*" * i)
greenlets = [
gevent.spawn(incoming),
gevent.spawn(send_a_bunch),
]
gevent.joinall(greenlets)
```
翻译者:兰玉磊
博客:http://www.lanyulei.com