from tornado import websocket, ioloop, gen, escape
class SocketClient():
def __init__(self):
self.headers = httputil.HTTPHeaders()
self.headers['Content-Type'] = 'application/json'
self.request = httpclient.HTTPRequest(
url = "wss://some.url",
validate_cert = False,
client_key = "client-key.pem",
client_cert = "client-cert.pem",
connect_timeout = 60,
request_timeout = 60)
def connect(self, connCallback, msgCallback):
self.request.headers = self.headers
self.__msgcallback = msgCallback
self.__conncallback = connCallback
wssConn = websocket.WebSocketClientConnection(ioloop.IOLoop.current(), self.request)
wssConn.connect_future.add_done_callback(self.__on_connResult)
def __on_connResult(self, conn):
if conn.exception() == None:
self.__wssConn = conn.result()
self.__conncallback(True)
self.__read()
else:
print(conn.exception().args)
self.__conncallback(False)
def send(self, data):
self.__wssConn.write_message(escape.utf8(json.dumps(data)))
@gen.coroutine
def __read(self):
while True:
msg = yield self.__wssConn.read_message()
if msg is None:
self.__conncallback(False)
break
self.__msgcallback(msg)
29 Ağustos 2013 Perşembe
Tornado websocket client
Tornado'nun sunucu hizmetleri ile ilgili bir sürü örnek var ama istemci olarak hele hele WebSocket için neredeyse hiçbir örnek bulamadım internette, onun için buraya yazalım dursun, bir gün birine lazım olur.
Kaydol:
Yorumlar (Atom)