简体   繁体   中英

Websocket connection with autobahn and twisted in python

I'm trying to use twiested with autobahn to connect to a websocket server

from autobahn.twisted.websocket import WebSocketClientProtocol


class OkcClient(WebSocketClientProtocol):
    def onOpen(self):
        #self.sendMessage(u"Hello, world!".encode('utf8'))
        self.sendMessage(u"{'event':'addChannel','channel':'ok_btcusd_future_ticker_this_week'}".encode('utf8'))
        self.sendMessage(u"{'event':'addChannel','channel':'ok_future_btcusd_kline_this_week_5min'}".encode('utf8'))

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))


import sys
from twisted.python import log
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory
log.startLogging(sys.stdout)
factory = WebSocketClientFactory("wss://real.okcoin.com:10440/websocket/okcoinapi")
factory.protocol = OkcClient

reactor.connectTCP("wss://real.okcoin.com/websocket/okcoinapi", 10440, factory)
reactor.run()

But the only thing I get out of this is the messages:

2014-11-18 11:45:39+0000 [-] Log opened.
2014-11-18 11:45:51+0000 [-] Starting factory <autobahn.twisted.websocket.WebSocketClientFactory instance at 0x106a0ccf8>
2014-11-18 11:46:04+0000 [-] Stopping factory <autobahn.twisted.websocket.WebSocketClientFactory instance at 0x106a0ccf8>

No matter what I tried, the factory closes as soon as I do a reactor.run()

reactor.connectTCP accepts as its first argument an IP address (or a hostname). You passed it a URI. It got confused and decided this must be a hostname, tried to resolve it, failed, and stopped the client factory.

Try passing real.okcoin.com instead of the full URI. This can be resolved to an IP address (I assume) and the connection attempt will be able to proceed further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM