How to use the autobahn.twisted.websocket.WebSocketServerProtocol function in autobahn

To help you get started, we’ve selected a few autobahn examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github crossbario / autobahn-python / examples / twisted / websocket / echo_wsgi / server.py View on Github external
from twisted.python import log
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource

from flask import Flask, render_template

from autobahn.twisted.websocket import WebSocketServerFactory, \
    WebSocketServerProtocol

from autobahn.twisted.resource import WebSocketResource, WSGIRootResource


# Our WebSocket Server protocol
class EchoServerProtocol(WebSocketServerProtocol):

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)


# Our WSGI application .. in this case Flask based
app = Flask(__name__)
app.secret_key = str(uuid.uuid4())


@app.route('/')
def page_home():
    return render_template('index.html')


if __name__ == "__main__":
github songrun / VectorSkinning / web-gui.py View on Github external
try:
	## New style autobahn
	from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
except ImportError:
	## Old style autobahn
	from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS

## All payloads are JSON-formatted.
import json
import src.parameters
from src.spline_computer import *
from src.tictoc import tic, toc, tictoc_dec
from itertools import izip as zip
from numpy import argmax

class WebGUIServerProtocol( WebSocketServerProtocol ):
	def connectionMade( self ):
		WebSocketServerProtocol.connectionMade( self )
		self.engine = self.factory.engine
		self.engine_type = 'ours'
		
		print 'CONNECTED'
	
	#@tictoc_dec
	def onMessage( self, msg, binary ):
		### BEGIN DEBUGGING
		if parameters.kVerbose >= 2:
			if not binary:
				from pprint import pprint
				space = msg.find( ' ' )
				if space == -1:
					print msg
github crossbario / autobahn-python / examples / twisted / websocket / echo_multicore / server.py View on Github external
def connectionLost(self, reason):
        WebSocketServerProtocol.connectionLost(self, reason)

        self.factory.stats.trackOctetsWireIn(self.trafficStats.preopenIncomingOctetsWireLevel +
                                             self.trafficStats.incomingOctetsWireLevel)

        self.factory.stats.trackOctetsWireOut(self.trafficStats.preopenOutgoingOctetsWireLevel +
                                              self.trafficStats.outgoingOctetsWireLevel)
github slush0 / stratum / stratum / websocket_transport.py View on Github external
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from protocol import Protocol
from event_handler import GenericEventHandler

class WebsocketServerProtocol(WebSocketServerProtocol, Protocol):
    def connectionMade(self):
        WebSocketServerProtocol.connectionMade(self)
        Protocol.connectionMade(self)
        
    def connectionLost(self, reason):
        WebSocketServerProtocol.connectionLost(self, reason)
        Protocol.connectionLost(self, reason)
        
    def onMessage(self, msg, is_binary):
        Protocol.dataReceived(self, msg)
            
    def transport_write(self, data):
        self.sendMessage(data, False)
        
class WebsocketTransportFactory(WebSocketServerFactory):
    def __init__(self, port, is_secure=False, debug=False, signing_key=None, signing_id=None,
github evennia / evennia / evennia / server / portal / webclient.py View on Github external
from evennia.server.session import Session
from evennia.utils.utils import to_str, mod_import
from evennia.utils.ansi import parse_ansi
from evennia.utils.text2html import parse_html
from autobahn.twisted.websocket import WebSocketServerProtocol

_RE_SCREENREADER_REGEX = re.compile(
    r"%s" % settings.SCREENREADER_REGEX_STRIP, re.DOTALL + re.MULTILINE
)
_CLIENT_SESSIONS = mod_import(settings.SESSION_ENGINE).SessionStore


CLOSE_NORMAL = WebSocketServerProtocol.CLOSE_STATUS_CODE_NORMAL


class WebSocketClient(WebSocketServerProtocol, Session):
    """
    Implements the server-side of the Websocket connection.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.protocol_key = "webclient/websocket"

    def get_client_session(self):
        """
        Get the Client browser session (used for auto-login based on browser session)

        Returns:
            csession (ClientSession): This is a django-specific internal representation
                of the browser session.
github crossbario / autobahn-python / examples / twisted / websocket / multiproto / server1.py View on Github external
class Echo2Service(BaseService):

    """
    Awesome Echo Service 2.
    """

    def onMessage(self, payload, isBinary):
        if not isBinary:
            msg = "Echo 2 - {}".format(payload.decode('utf8'))
            print(msg)
            self.proto.sendMessage(msg.encode('utf8'))


class ServiceServerProtocol(WebSocketServerProtocol):

    SERVICEMAP = {'/echo1': Echo1Service,
                  '/echo2': Echo2Service}

    def __init__(self):
        self.service = None
        self.is_closed = txaio.create_future()

    def onConnect(self, request):
        # request has all the information from the initial
        # WebSocket opening handshake ..
        print(request.peer)
        print(request.headers)
        print(request.host)
        print(request.path)
        print(request.params)
github slush0 / stratum / stratum / websocket_transport.py View on Github external
def connectionMade(self):
        WebSocketServerProtocol.connectionMade(self)
        Protocol.connectionMade(self)
github AGProjects / sylkserver / sylk / applications / webrtcgateway / protocol.py View on Github external
import json

from application.notification import NotificationCenter, NotificationData
from autobahn.twisted.websocket import WebSocketServerProtocol
from autobahn.websocket import ConnectionDeny

from .handler import ConnectionHandler
from .janus import JanusBackend
from .logger import log


SYLK_WS_PROTOCOL = 'sylkRTC-2'


class SylkWebSocketServerProtocol(WebSocketServerProtocol):
    janus_backend = JanusBackend()
    connection_handler = None

    notification_center = NotificationCenter()

    def onConnect(self, request):
        if SYLK_WS_PROTOCOL not in request.protocols:
            log.debug('Connection from {} request: {}'.format(self.peer, request))
            log.info('Rejecting connection from {}, client uses unsupported protocol: {}'.format(self.peer, ','.join(request.protocols)))
            raise ConnectionDeny(406, u'No compatible protocol specified')
        if not self.janus_backend.ready:
            log.warning('Rejecting connection from {}, Janus backend is not connected'.format(self.peer))
            raise ConnectionDeny(503, u'Backend is not connected')
        return SYLK_WS_PROTOCOL

    def onOpen(self):
github pajbot / pajbot / pajbot / managers / websocket.py View on Github external
def __init__(self, manager, port, secure=False, key_path=None, crt_path=None, unix_socket_path=None):
        self.manager = manager
        from twisted.internet import reactor, ssl

        from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol

        class MyServerProtocol(WebSocketServerProtocol):
            def onConnect(self, request):
                # log.info(self.factory)
                # log.info('Client connecting: {0}'.format(request.peer))
                pass

            def onOpen(self):
                log.info("WebSocket connection open")
                WebSocketServer.clients.append(self)

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

            def onClose(self, wasClean, code, reason):