def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) print str(self) + "connected" SUBSCRIBERS.add(self) global NextUID NextUID = NextUID + 1 UID = NextUID
def __init__(self, url, protocols, extensions): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16)) self.url = url
def __init__(self, *args, **kwargs): self.widget_wslock = threading.Lock() # We don't know what DB they are connected to self.db = None self.session = drayerdb.Session(isClientSide=True) WebSocket.__init__(self, *args, **kwargs)
def __init__(self, *args, **kw): """ Constructor. This will be called automatically by the server upon connection """ WebSocket.__init__(self, *args, **kw) self.close_callback = None
def __init__(self, *args, **kwargs): """ This passes all arguments to the parent constructor. In addition, it defines the following instance variables: send_lock: Used to guarantee thread-safety when sending RPC responses. client_locks: A dict mapping client ids to locks used by those clients. passthru_subscriptions: When we recieve a subscription request for a service method registered on a remote service, we pass that request along to the remote service and send back the responses. This dictionary maps client ids to those subscription objects. session_fields: We copy session data for the currently-authenticated user who made the incoming websocket connection; by default we only copy the username, but this can be overridden in configuration. Remember that Sideboard exposes two websocket handlers at /ws and /wsrpc, with /ws being auth-protected (so the username field will be meaningful) and /wsrpc being client-cert protected (so the username will always be 'rpc'). header_fields: We copy header fields from the request that initiated the websocket connection. cached_queries and cached_fingerprints: When we receive a subscription update, Sideboard re-runs all of the subscription methods to see if new data needs to be pushed out. We do this by storing all of the rpc methods and an MD5 hash of their return values. We store a hash rather than the return values themselves to save on memory, since return values may be very large. The cached_queries dict has this structure: { 'client_id': { 'callback_id': (func, args, kwargs, client_data), ... }, ... } The cached_fingerprints dict has this structure: { 'client_id': { 'callback_id': 'md5_hash_of_return_value', ... }, ... } """ WebSocket.__init__(self, *args, **kwargs) self.instances.add(self) self.send_lock = RLock() self.passthru_subscriptions = {} self.client_locks = defaultdict(RLock) self.cached_queries, self.cached_fingerprints = defaultdict( dict), defaultdict(dict) self.session_fields = self.check_authentication() self.header_fields = self.fetch_headers()
def __init__(self, app_name, *args, **kw): self.app_name = app_name self.backend = get_backend() self.verbose = self.backend.verbose cherrypy.log.access_log.info( 'Creating %s with args=%s and keywords=%s.' % (self.app_name, args, kw)) WebSocket.__init__(self, *args, **kw) self.backend.register(self)
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): WebSocket.__init__(self, sock, protocols, extensions, environ, heartbeat_freq)
def __init__(self, *args, **kwargs): """ This passes all arguments to the parent constructor. In addition, it defines the following instance variables: send_lock: Used to guarantee thread-safety when sending RPC responses. client_locks: A dict mapping client ids to locks used by those clients. passthru_subscriptions: When we recieve a subscription request for a service method registered on a remote service, we pass that request along to the remote service and send back the responses. This dictionary maps client ids to those subscription objects. session_fields: We copy session data for the currently-authenticated user who made the incoming websocket connection; by default we only copy the username, but this can be overridden in configuration. Remember that Sideboard exposes two websocket handlers at /ws and /wsrpc, with /ws being auth-protected (so the username field will be meaningful) and /wsrpc being client-cert protected (so the username will always be 'rpc'). header_fields: We copy header fields from the request that initiated the websocket connection. cached_queries and cached_fingerprints: When we receive a subscription update, Sideboard re-runs all of the subscription methods to see if new data needs to be pushed out. We do this by storing all of the rpc methods and an MD5 hash of their return values. We store a hash rather than the return values themselves to save on memory, since return values may be very large. The cached_queries dict has this structure: { 'client_id': { 'callback_id': (func, args, kwargs, client_data), ... }, ... } The cached_fingerprints dict has this structure: { 'client_id': { 'callback_id': 'md5_hash_of_return_value', ... }, ... } """ WebSocket.__init__(self, *args, **kwargs) self.instances.add(self) self.send_lock = RLock() self.passthru_subscriptions = {} self.client_locks = defaultdict(RLock) self.cached_queries, self.cached_fingerprints = defaultdict(dict), defaultdict(dict) self.session_fields = self.check_authentication() self.header_fields = self.fetch_headers()
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): WebSocket.__init__(self, sock, protocols, extensions, environ, heartbeat_freq) self.json_rpc = cherrypy.engine.json_rpc
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): WebSocket.__init__(self, sock) self.clients = [] self.settings = cherrypy.engine.publish('get-settings', 'gui')[0] self.type = 'gui'
def __init__(self, *args, **kargs): WebSocket.__init__(self, *args, **kargs) self._logger = logging.getLogger('python') self.comMessage = { "sender": "python", "opCode": "info", "data": { "param": 0, "discription": '' } } print("_________init_________")
def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) # cherrypy.log("args type %s" % type(ws)) # # for i in args: # try: # cherrypy.log("args %s \n" % i) # except Exception as error: # cherrypy.log("Can't print args because %s \n" % error) # cherrypy.log("args %s " % args) # cherrypy.log("kw %s " % kw) SUBSCRIBERS.add(self)
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.debugger_store().chrome_channel.setSocket(self) common_domain_args = {'debugger_store': self.debugger_store()} runtime_domain = RuntimeDomain(**common_domain_args) debugger_domain = DebuggerDomain(runtime_domain, **common_domain_args) self.handlers = HandlerDomainSet( ConsoleDomain(**common_domain_args), debugger_domain, PageDomain(**common_domain_args), runtime_domain, )
def __init__(self, url, protocols, extensions, heartbeat_freq=None): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16)) self.url = url self.host = None self.scheme = None self.port = None self.resource = None self._parse_url()
def __init__(self, *args, **kargs): WebSocket.__init__(self, *args, **kargs) self.isAlive = True self._logger = logging.getLogger('python') self.comMessage = { "sender": "python", "opCode": "info", "data": { "param": 0, "discription": '' } } self._serialThread = threading.Thread(target=self.serialLoop, name="wait serial data") self._serialThread.start() print("_________init_________")
def __init__(self, *args, **kargs): '''New websockets can be registered with the radio on creation. Channel names can be passed in the URL, for example: ws://localhost:1002/ws/chan0/chan1 A socket may be created with no channels, and then register one or more later on. This is how client-side Radio actually works. ''' WebSocket.__init__(self, *args, **kargs) # derive a list of zero or more channels from the url channels = str(self.environ['REQUEST_URI'])[2:-1].split('/')[2:] # if channels is empty, this does nothing radio.register(channels, self.send, True)
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.debugger_store().chrome_channel.setSocket(self) common_domain_args = { 'debugger_store': self.debugger_store() } runtime_domain = RuntimeDomain(**common_domain_args) debugger_domain = DebuggerDomain( runtime_domain, **common_domain_args) self.handlers = HandlerDomainSet( ConsoleDomain(**common_domain_args), debugger_domain, PageDomain(**common_domain_args), runtime_domain, )
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created with the nagle's algorithm disabled and with the capacity to reuse a port that was just used. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16)) self.url = url self.host = None self.scheme = None self.port = None self.resource = None self._parse_url()
def __init__(self, proto): """ A :pep:`3156` ready websocket handler that works well in a coroutine-aware loop such as the one provided by the asyncio module. The provided `proto` instance is a :class:`asyncio.Protocol` subclass instance that will be used internally to read and write from the underlying transport. Because the base :class:`ws4py.websocket.WebSocket` class is still coupled a bit to the socket interface, we have to override a little more than necessary to play nice with the :pep:`3156` interface. Hopefully, some day this will be cleaned out. """ _WebSocket.__init__(self, None) self.started = False self.proto = proto
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) common_domain_args = { 'debugger': self.debugger(), 'socket': self, } file_manager = FileManager(self) remote_object_manager = RemoteObjectManager() runtime_domain = RuntimeDomain(remote_object_manager, **common_domain_args) self.handlers = HandlerDomainSet( ConsoleDomain(**common_domain_args), DebuggerDomain(runtime_domain, file_manager, remote_object_manager, basepath=self.basepath(), **common_domain_args), PageDomain(**common_domain_args), runtime_domain, )
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) common_domain_args = { 'debugger': self.debugger(), 'socket': self, } file_manager = FileManager(self) remote_object_manager = RemoteObjectManager() runtime_domain = RuntimeDomain( remote_object_manager, **common_domain_args) self.handlers = HandlerDomainSet( ConsoleDomain(**common_domain_args), DebuggerDomain( runtime_domain, file_manager, remote_object_manager, basepath=self.basepath(), **common_domain_args), PageDomain(**common_domain_args), runtime_domain, )
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None, headers=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created. If the connection is a TCP socket, the nagle's algorithm is disabled. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. For instance to create a TCP client: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws://localhost/ws') Here is an example for a TCP client over SSL: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('wss://localhost/ws') Finally an example of a Unix-domain connection: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') Note that in this case, the initial Upgrade request will be sent to ``/``. You may need to change this by setting the resource explicitely before connecting: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') >>> ws.resource = '/ws' >>> ws.connect() You may provide extra headers by passing a list of tuples which must be unicode objects. """ self.url = url self.host = None self.scheme = None self.port = None self.unix_socket_path = None self.resource = None self.ssl_options = ssl_options or {} self.extra_headers = headers or [] self._parse_url() if self.unix_socket_path: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) else: # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: family, socktype, proto, canonname, sa = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 canonname = "" sa = (self.host, self.port, 0, 0) sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and \ self.host.startswith('::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) SUBSCRIBERS.add(self)
def __init__(self, *args, **kwargs): WebSocket.__init__(self,*args,**kwargs) self.service = JamrService()
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.session_id = None
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.controller = AuthenticateMessageController() self.user = None self.greenlet_listener = None self.is_open= False
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.session_token = None self.role = None
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=30.0): WebSocket.__init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=heartbeat_freq) self.hb = Heartbeat(self, 30.0) self.hb.setDaemon(True) self.hb.start()
def __init__( self, *args, **kw ): WebSocket.__init__( self, *args, **kw )
def __init__(self,*args,**kwargs): self.subscriptions = [] self.lastPushedNewData = 0 self.uuid = "id"+base64.b64encode(os.urandom(16)).decode().replace("/",'').replace("-",'').replace('+','')[:-2] WebSocket.__init__(self,*args,**kwargs)
def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) self._wsKey = args[3]['HTTP_SEC_WEBSOCKET_KEY'] _clients[self._wsKey] = self
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.send_lock = RLock() self.client_locks, self.cached_queries, self.cached_fingerprints = \ defaultdict(RLock), defaultdict(dict), defaultdict(dict) self.username = self.check_authentication()
def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) print str(self) + "connected" SUBSCRIBERS.add(self)
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created with the nagle's algorithm disabled and with the capacity to reuse a port that was just used. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. """ self.url = url self.host = None self.scheme = None self.port = None self.resource = None self._parse_url() # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: family, socktype, proto, canonname, sa = socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 canonname = "" sa = (self.host, self.port, 0, 0) sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and \ self.host.startswith('::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, *args, **kw): print 'Publisher().__init__...' WebSocket.__init__(self, *args, **kw) SUBSCRIBERS.add(self)
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): WebSocket.__init__(self, sock) self.daemon = True self.clients = [] self.type = 'chat'
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) self.service = JamrService()
def __init__(self,*args,**kwargs): self.subscriptions = [] self.lastPushedNewData = 0 WebSocket.__init__(self,*args,**kwargs)
def __init__(self, *args, **kw): WebSocket.__init__( self, *args, **kw ) global counter self.id = counter
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None, headers=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created. If the connection is a TCP socket, the nagle's algorithm is disabled. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. For instance to create a TCP client: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws://localhost/ws') Here is an example for a TCP client over SSL: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('wss://localhost/ws') Finally an example of a Unix-domain connection: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') Note that in this case, the initial Upgrade request will be sent to ``/``. You may need to change this by setting the resource explicitely before connecting: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') >>> ws.resource = '/ws' >>> ws.connect() You may provide extra headers by passing a list of tuples which must be unicode objects. """ self.url = url self.host = None self.scheme = None self.port = None self.unix_socket_path = None self.resource = None self.ssl_options = ssl_options or {} self.extra_headers = headers or [] self.sa = None self._parse_url() WebSocket.__init__(self, None, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, connections, handler_id, sock, protocols, extensions, environ): WebSocket.__init__(self, sock, protocols, extensions, environ) self.connections = connections self.handler_id = handler_id
def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, environ=environ, heartbeat_freq=heartbeat_freq) self.tcp_endpoint = PadWSProxyTCPEndpoint(self) self.tcp_endpoint.thread.start()
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created. If the connection is a TCP socket, the nagle's algorithm is disabled. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. For instance to create a TCP client: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws://localhost/ws') Here is an example for a TCP client over SSL: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('wss://localhost/ws') Finally an example of a Unix-domain connection: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') Note that in this case, the initial Upgrade request will be sent to ``/``. You may need to change this by setting the resource explicitely before connecting: .. code-block:: python >>> from websocket.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') >>> ws.resource = '/ws' >>> ws.connect() """ self.url = url self.host = None self.scheme = None self.port = None self.unix_socket_path = None self.resource = None self.ssl_options = ssl_options or {} self._parse_url() if self.unix_socket_path: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) else: # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: family, socktype, proto, canonname, sa = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 canonname = "" sa = (self.host, self.port, 0, 0) sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and \ self.host.startswith('::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created with the nagle's algorithm disabled and with the capacity to reuse a port that was just used. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. """ self.url = url self.host = None self.scheme = None self.port = None self.resource = None self.ssl_options = ssl_options or {} self._parse_url() # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: family, socktype, proto, canonname, sa = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 canonname = "" sa = (self.host, self.port, 0, 0) sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and \ self.host.startswith('::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, url, *args, **kwargs): self.client = kwargs.pop('client') reserved_ports = kwargs.pop('reserved_ports') reserved_ports_blacklist = kwargs.pop('reserved_ports_blacklist') self.reserved_fd = None self.protocol = DDPProtocol(self) if not reserved_ports: super(WSClient, self).__init__(url, *args, **kwargs) else: """ All this code has been copied from WebSocketClient.__init__ because it is not prepared to handle a custom socket via method overriding. We need to use socket.fromfd in case reserved_ports is specified. """ self.url = url self.host = None self.scheme = None self.port = None self.unix_socket_path = None self.resource = None self.ssl_options = kwargs.get('ssl_options') or {} self.extra_headers = kwargs.get('headers') or [] self.exclude_headers = kwargs.get('exclude_headers') or [] self.exclude_headers = [x.lower() for x in self.exclude_headers] if self.scheme == "wss": # Prevent check_hostname requires server_hostname (ref #187) if "cert_reqs" not in self.ssl_options: self.ssl_options["cert_reqs"] = ssl.CERT_NONE self._parse_url() if self.unix_socket_path: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) else: # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: family, socktype, proto, canonname, sa = socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 """ This is the line replaced to use socket.fromfd """ try: self.reserved_fd = self.get_reserved_portfd( blacklist=reserved_ports_blacklist) sock = socket.fromfd(self.reserved_fd, family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr( socket, 'AF_INET6' ) and family == socket.AF_INET6 and self.host.startswith( '::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass except Exception as e: if self.reserved_fd: try: os.close(self.reserved_fd) except OSError: pass raise e WebSocket.__init__(self, sock, protocols=kwargs.get('protocols'), extensions=kwargs.get('extensions'), heartbeat_freq=kwargs.get('heartbeat_freq')) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16)) self._th = threading.Thread(target=self.run, name='WebSocketClient') self._th.daemon = True
def __init__(self, *args, **kwargs): WebSocket.__init__(self, *args, **kwargs) _subscribers.add(self)
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None, headers=None, exclude_headers=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will block if not run in its own thread. When an instance of this class is created, a :py:mod:`socket` is created. If the connection is a TCP socket, the nagle's algorithm is disabled. The address of the server will be extracted from the given websocket url. The websocket key is randomly generated, reset the `key` attribute if you want to provide yours. For instance to create a TCP client: .. code-block:: python >>> from ws4py.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws://localhost/ws') Here is an example for a TCP client over SSL: .. code-block:: python >>> from ws4py.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('wss://localhost/ws') Finally an example of a Unix-domain connection: .. code-block:: python >>> from ws4py.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') Note that in this case, the initial Upgrade request will be sent to ``/``. You may need to change this by setting the resource explicitely before connecting: .. code-block:: python >>> from ws4py.client import WebSocketBaseClient >>> ws = WebSocketBaseClient('ws+unix:///tmp/my.sock') >>> ws.resource = '/ws' >>> ws.connect() You may provide extra headers by passing a list of tuples which must be unicode objects. """ self.url = url self.host = None self.scheme = None self.port = None self.unix_socket_path = None self.resource = None self.ssl_options = ssl_options or {} self.extra_headers = headers or [] self.exclude_headers = exclude_headers or [] self.exclude_headers = [x.lower() for x in self.exclude_headers] if self.scheme == "wss": # Prevent check_hostname requires server_hostname (ref #187) if "cert_reqs" not in self.ssl_options: self.ssl_options["cert_reqs"] = ssl.CERT_NONE self._parse_url() if self.unix_socket_path: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) else: # Let's handle IPv4 and IPv6 addresses # Simplified from CherryPy's code try: addrinfo = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) except socket.gaierror: family = socket.AF_INET if self.host.startswith('::'): family = socket.AF_INET6 socktype = socket.SOCK_STREAM proto = 0 canonname = "" sa = (self.host, self.port, 0, 0) addrinfo = [(family, socktype, proto, canonname, sa)] for family, socktype, proto, canonname, sa in addrinfo: sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'AF_INET6') and family == socket.AF_INET6 and \ self.host.startswith('::'): try: sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) except (AttributeError, socket.error): pass if self.scheme == "wss": # default port is now 443; upgrade self.sender to send ssl sock = ssl.wrap_socket(self.sock, **self.ssl_options) self._is_secure = True try: sock.connect(self.bind_addr) break except socket.error as err: sock = None continue if sock is None: raise err WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions, heartbeat_freq=heartbeat_freq) self.stream.always_mask = True self.stream.expect_masking = False self.key = b64encode(os.urandom(16))
def __init__(self, *args, **kw): WebSocket.__init__(self, *args, **kw) self.username = None