1############################################################################### 2# 3# The MIT License (MIT) 4# 5# Copyright (c) Crossbar.io Technologies GmbH 6# 7# Permission is hereby granted, free of charge, to any person obtaining a copy 8# of this software and associated documentation files (the "Software"), to deal 9# in the Software without restriction, including without limitation the rights 10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11# copies of the Software, and to permit persons to whom the Software is 12# furnished to do so, subject to the following conditions: 13# 14# The above copyright notice and this permission notice shall be included in 15# all copies or substantial portions of the Software. 16# 17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23# THE SOFTWARE. 24# 25############################################################################### 26 27import sys 28from optparse import OptionParser 29 30from twisted.python import log 31from twisted.internet import reactor, ssl 32 33from autobahn.twisted.websocket import WebSocketClientFactory, \ 34 WebSocketClientProtocol, \ 35 connectWS 36 37 38class EchoClientProtocol(WebSocketClientProtocol): 39 40 def sendHello(self): 41 self.sendMessage("Hello, world!".encode('utf8')) 42 43 def onOpen(self): 44 self.sendHello() 45 46 def onMessage(self, payload, isBinary): 47 if not isBinary: 48 print("Text message received: {}".format(payload.decode('utf8'))) 49 reactor.callLater(1, self.sendHello) 50 51 52if __name__ == '__main__': 53 54 log.startLogging(sys.stdout) 55 56 parser = OptionParser() 57 parser.add_option("-u", "--url", dest="url", help="The WebSocket URL", default="wss://127.0.0.1:9000") 58 (options, args) = parser.parse_args() 59 60 # create a WS server factory with our protocol 61 ## 62 factory = WebSocketClientFactory(options.url) 63 factory.protocol = EchoClientProtocol 64 65 # SSL client context: default 66 ## 67 if factory.isSecure: 68 contextFactory = ssl.ClientContextFactory() 69 else: 70 contextFactory = None 71 72 connectWS(factory, contextFactory) 73 reactor.run() 74