Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import txaio
txaio.use_twisted()
from twisted.internet import reactor
import autobahn
from autobahn.twisted.websocket import connectWS, WebSocketClientFactory, \
WebSocketClientProtocol
from autobahn.websocket.compress import PerMessageDeflateOffer, \
PerMessageDeflateResponse, PerMessageDeflateResponseAccept
class TesteeClientProtocol(WebSocketClientProtocol):
def onOpen(self):
if self.factory.endCaseId is None:
self.log.info("Getting case count ..")
elif self.factory.currentCaseId <= self.factory.endCaseId:
self.log.info("Running test case {case_id}/{last_case_id} as user agent {agent} on peer {peer}",
case_id=self.factory.currentCaseId,
last_case_id=self.factory.endCaseId,
agent=self.factory.agent,
peer=self.peer)
def onMessage(self, msg, binary):
if self.factory.endCaseId is None:
self.factory.endCaseId = int(msg)
self.log.info("Ok, will run {case_count} cases", case_count=self.factory.endCaseId)
else:
# this function gets called every time connectWS is called (once per WebSocket connection/session)
def buildProtocol(self, addr):
try:
utt = self.queueProto.get_nowait()
proto = WSInterfaceProtocol(self, self.queue, self.summary, self.contentType)
proto.setUtterance(utt)
return proto
except Queue.Empty:
print "queue should not be empty, otherwise this function should not have been called"
return None
# WebSockets interface to the STT service
# note: an object of this class is created for each WebSocket connection, every time we call connectWS
class WSInterfaceProtocol(WebSocketClientProtocol):
def __init__(self, factory, queue, summary, contentType):
self.factory = factory
self.queue = queue
self.summary = summary
self.contentType = contentType
self.packetRate = 20
self.listeningMessages = 0
self.timeFirstInterim = -1
self.bytesSent = 0
self.chunkSize = 2000 # in bytes
super(self.__class__, self).__init__()
# print "contentType: " + str(self.contentType) + " queueSize: " + str(self.queue.qsize())
def setUtterance(self, utt):
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
if __name__ == '__main__':
log.startLogging(sys.stdout)
if len(sys.argv) < 2:
print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000")
sys.exit(1)
factory = WebSocketClientFactory(sys.argv[1])
factory.protocol = WebSocketClientProtocol
connectWS(factory)
reactor.run()
self.message_callback = None
self.close_callback = None
self.log_id = log_id
self.intercepting_macros = None
self.parent_http_proxy = parent_proxy
# The raw http messages from the handshake
self.client_handshake = client_handshake
self.server_handshake = server_handshake
self.server_factory = WebSocketServerFactory()
self.server_factory.protocol = WebSocketServerProtocol
self.server_transport = server_transport
self.client_factory = WebSocketClientFactory()
self.client_factory.protocol = WebSocketClientProtocol
self.client_transport = client_transport
self._fake_handshake()
PBTwitterManager.bot = bot
PBTwitterManager.tweepy = self.twitter_client
self.listener = PBTwitterManager
if "twitter" not in bot.config:
return
self.reload()
log.info("pajbot twitter manager initialized")
from twisted.internet import reactor
class ClientProtocol(WebSocketClientProtocol):
def onOpen(self):
PBTwitterManager.client = self
log.info("Connected to tweet-provider")
user_ids = [PBTwitterManager.tweepy.get_user(screen_name=e).id for e in PBTwitterManager.relevant_users]
msg = {"type": "set_subscriptions", "data": user_ids}
self.sendMessage(json.dumps(msg).encode("utf8"))
def onMessage(self, payload, isBinary):
if isBinary:
return
message = json.loads(payload)
def __init__(self):
super(WebSocketClientProtocol, self).__init__()
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
from ranstring import randomByteString
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
MESSAGE_SIZE = 1 * 2**20
class MessageBasedHashClientProtocol(WebSocketClientProtocol):
"""
Message-based WebSockets client that generates stream of random octets
sent to WebSockets server as a sequence of messages. The server will
respond to us with the SHA-256 computed over each message. When
we receive response, we repeat by sending a new message.
"""
def sendOneMessage(self):
data = randomByteString(MESSAGE_SIZE)
self.sendMessage(data, isBinary=True)
def onOpen(self):
self.count = 0
self.sendOneMessage()
def pushDatapoint(self, data):
factory = PredixTimeSeriesFactory(self.endpoint, origin=self.origin, headers=self.headers, payload=data)
factory.protocol = PredixTimeSeriesProtocol
ssl_ctx = ssl.ClientContextFactory()
connectWS(factory, ssl_ctx)
class PredixTimeSeriesFactory(WebSocketClientFactory):
def __init__(self, endpoint, origin, headers, payload):
super(PredixTimeSeriesFactory, self).__init__(endpoint, origin=origin, headers=headers)
self.payload = payload
class PredixTimeSeriesProtocol(WebSocketClientProtocol):
def __init__(self):
super(PredixTimeSeriesProtocol, self).__init__()
self.message_id = str(uuid4())
def onConnect(self, response):
print(response)
def onOpen(self):
print("Connected to Predix Time Series service.")
self.pushDatapoint()
def onClose(self, clean, code, reason):
def start(self):
"Connect protocol to remote server"
try:
from twisted.internet import ssl
except ImportError:
log_err("To use Grapevine, The PyOpenSSL module must be installed.")
else:
context_factory = ssl.ClientContextFactory() if self.isSecure else None
connectWS(self, context_factory)
# service.name = "websocket/grapevine"
# self.sessionhandler.portal.services.addService(service)
class GrapevineClient(WebSocketClientProtocol, Session):
"""
Implements the grapevine client
"""
def __init__(self):
WebSocketClientProtocol.__init__(self)
Session.__init__(self)
self.restart_downtime = None
def at_login(self):
pass
def onOpen(self):
"""
Called when connection is established.
def new_websocket(self, websocket_id):
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
form = self
class PytigonClientProtocol(WebSocketClientProtocol):
def __init__(self):
nonlocal form, websocket_id
super().__init__()
self.form = form
self.websocket_id = websocket_id
form.websockets[websocket_id] = self
def onConnect(self, response):
self.form.on_websocket_connect(self, self.websocket_id, response)
def onOpen(self):
self.form.on_websocket_open(self, self.websocket_id)
def onMessage(self, msg, binary):
self.form.on_websocket_message(self, websocket_id, msg, binary)