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 27from ranstring import randomByteString 28from twisted.internet import reactor 29 30from autobahn.twisted.websocket import WebSocketClientFactory, \ 31 WebSocketClientProtocol, \ 32 connectWS 33 34MESSAGE_SIZE = 1 * 2**20 35 36 37class MessageBasedHashClientProtocol(WebSocketClientProtocol): 38 39 """ 40 Message-based WebSockets client that generates stream of random octets 41 sent to WebSockets server as a sequence of messages. The server will 42 respond to us with the SHA-256 computed over each message. When 43 we receive response, we repeat by sending a new message. 44 """ 45 46 def sendOneMessage(self): 47 data = randomByteString(MESSAGE_SIZE) 48 self.sendMessage(data, isBinary=True) 49 50 def onOpen(self): 51 self.count = 0 52 self.sendOneMessage() 53 54 def onMessage(self, payload, isBinary): 55 print("Digest for message {} computed by server: {}".format(self.count, payload.decode('utf8'))) 56 self.count += 1 57 self.sendOneMessage() 58 59 60if __name__ == '__main__': 61 62 factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") 63 factory.protocol = MessageBasedHashClientProtocol 64 connectWS(factory) 65 reactor.run() 66