## 客戶端
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