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 28 29from twisted.internet import reactor 30from twisted.internet.protocol import ReconnectingClientFactory 31from twisted.python import log 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 52class EchoClientFactory(ReconnectingClientFactory, WebSocketClientFactory): 53 54 protocol = EchoClientProtocol 55 56 # http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.ReconnectingClientFactory.html 57 # 58 maxDelay = 10 59 maxRetries = 5 60 61 def startedConnecting(self, connector): 62 print('Started to connect.') 63 64 def clientConnectionLost(self, connector, reason): 65 print('Lost connection. Reason: {}'.format(reason)) 66 ReconnectingClientFactory.clientConnectionLost(self, connector, reason) 67 68 def clientConnectionFailed(self, connector, reason): 69 print('Connection failed. Reason: {}'.format(reason)) 70 ReconnectingClientFactory.clientConnectionFailed(self, connector, reason) 71 72 73if __name__ == '__main__': 74 75 if len(sys.argv) < 2: 76 print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000") 77 sys.exit(1) 78 79 log.startLogging(sys.stdout) 80 81 factory = EchoClientFactory(sys.argv[1]) 82 connectWS(factory) 83 84 reactor.run() 85