more work on asyncio

This commit is contained in:
Tobias Oberstein
2013-12-23 15:22:36 +01:00
parent a731544a98
commit 0370136687
12 changed files with 642 additions and 413 deletions

View File

@@ -16,7 +16,8 @@ clean:
rm -rf ./autobahn.egg-info
rm -rf ./build
rm -rf ./dist
find . -name "*.pyc" -exec rm -f {} \;
find . -name "*.pyc" -type f -exec rm -f {} \;
find . -name "*__pycache__" -type d -exec rm -rf {} \;
build: clean
python setup.py bdist_egg

View File

@@ -16,13 +16,32 @@
##
###############################################################################
__all__ = ['WebSocketServerProtocol',
'WebSocketServerFactory',
'WebSocketClientProtocol',
'WebSocketClientFactory']
import asyncio
import inspect
from autobahn.websocket import protocol
from autobahn.websocket import http
def yields(value):
"""
Return True iff the value yields.
See: http://stackoverflow.com/questions/20730248/maybedeferred-analog-with-asyncio
"""
return isinstance(value, asyncio.futures.Future) or inspect.isgenerator(value)
class WebSocketServerProtocol(protocol.WebSocketServerProtocol, asyncio.Protocol):
"""
Base class for Asyncio WebSocket server protocols.
"""
def connection_made(self, transport):
self.transport = transport
@@ -49,9 +68,30 @@ class WebSocketServerProtocol(protocol.WebSocketServerProtocol, asyncio.Protocol
self.transport.close()
def _run_onConnect(self, connectionRequest):
res = self.onConnect(connectionRequest)
self._processHandshake_buildResponse(res)
#@asyncio.coroutine
def _onConnect(self, connectionRequest):
## onConnect() will return the selected subprotocol or None
## or a pair (protocol, headers) or raise an HttpException
##
try:
print("-"*10)
#res = yield from self.onConnect(connectionRequest)
res = self.onConnect(connectionRequest)
print(res)
print("*"*10)
#if yields(res):
# print("here")
# res = yield from res
#else:
# print("NOOO")
except http.HttpException as exc:
print(exc)
self.failHandshake(exc.reason, exc.code)
except Exception as exc:
print(exc)
self.failHandshake(http.INTERNAL_SERVER_ERROR[1], http.INTERNAL_SERVER_ERROR[0])
else:
self.succeedHandshake(res)
def registerProducer(self, producer, streaming):
@@ -60,6 +100,9 @@ class WebSocketServerProtocol(protocol.WebSocketServerProtocol, asyncio.Protocol
class WebSocketServerFactory(protocol.WebSocketServerFactory):
"""
Base class for Asyncio WebSocket server factories.
"""
def __init__(self, *args, **kwargs):
@@ -83,3 +126,68 @@ class WebSocketServerFactory(protocol.WebSocketServerFactory):
proto = self.protocol()
proto.factory = self
return proto
class WebSocketClientProtocol(protocol.WebSocketClientProtocol, asyncio.Protocol):
"""
Base class for Asyncio WebSocket client protocols.
"""
def connection_made(self, transport):
self.transport = transport
peer = transport.get_extra_info('peername')
try:
self.peer = "%s:%d" % (peer[0], peer[1])
except:
## eg Unix Domain sockets don't have host/port
self.peer = str(peer)
protocol.WebSocketClientProtocol.connectionMade(self)
def connection_lost(self, exc):
self.connectionLost(exc)
def data_received(self, data):
self.dataReceived(data)
def _closeConnection(self, abort = False):
self.transport.close()
def registerProducer(self, producer, streaming):
raise Exception("not implemented")
class WebSocketClientFactory(protocol.WebSocketClientFactory):
"""
Base class for Asyncio WebSocket client factories.
"""
def __init__(self, *args, **kwargs):
protocol.WebSocketClientFactory.__init__(self, *args, **kwargs)
if 'loop' in kwargs:
self.loop = kwargs['loop']
else:
self.loop = asyncio.get_event_loop()
def _log(self, msg):
print(msg)
def _callLater(self, delay, fun):
return self.loop.call_later(delay, fun)
def __call__(self):
proto = self.protocol()
proto.factory = self
return proto

View File

@@ -18,16 +18,24 @@
from __future__ import absolute_import
__all__ = ['WebSocketServerProtocol',
'WebSocketServerFactory',
'WebSocketClientProtocol',
'WebSocketClientFactory',
'listenWS',
'connectWS']
import twisted.internet.protocol
from twisted.internet.defer import maybeDeferred
from twisted.python import log
from autobahn.websocket import protocol
from autobahn.websocket import http
class WebSocketServerProtocol(protocol.WebSocketServerProtocol, twisted.internet.protocol.Protocol):
"""
Base class for Twisted WebSocket server protocols.
"""
def connectionMade(self):
@@ -49,18 +57,6 @@ class WebSocketServerProtocol(protocol.WebSocketServerProtocol, twisted.internet
pass
# peername = str(self.transport.getPeer())
# print('connection from {}'.format(peername))
# def dataReceived(self, data):
# self._onData(data)
# #print('data received: {}'.format(data.decode()))
# #self.transport.write(data)
# #self.transport.loseConnection()
# def connectionLost(self, reason):
# pass
def _closeConnection(self, abort = False):
if abort:
self.transport.abortConnection()
@@ -68,14 +64,23 @@ class WebSocketServerProtocol(protocol.WebSocketServerProtocol, twisted.internet
self.transport.loseConnection()
def _run_onConnect(self, connectionRequest):
def _onConnect(self, connectionRequest):
## onConnect() will return the selected subprotocol or None
## or a pair (protocol, headers) or raise an HttpException
##
res = maybeDeferred(self.onConnect, connectionRequest)
res.addCallback(self._processHandshake_buildResponse)
res.addErrback(self._processHandshake_failed)
res.addCallback(self.succeedHandshake)
def forwardError(failure):
if failure.check(http.HttpException):
return self.failHandshake(failure.value.reason, failure.value.code)
else:
if True or self.debug:
self.factory._log("Unexpected exception in onConnect ['%s']" % failure.value)
return self.failHandshake(http.INTERNAL_SERVER_ERROR[1], http.INTERNAL_SERVER_ERROR[0])
res.addErrback(forwardError)
def registerProducer(self, producer, streaming):
@@ -93,15 +98,13 @@ class WebSocketServerProtocol(protocol.WebSocketServerProtocol, twisted.internet
class WebSocketServerFactory(protocol.WebSocketServerFactory, twisted.internet.protocol.ServerFactory):
"""
Base class for Twisted WebSocket server factories.
"""
def __init__(self, *args, **kwargs):
#twisted.internet.protocol.ServerFactory.__init__(self)
protocol.WebSocketServerFactory.__init__(self, *args, **kwargs)
## lazy import to avoid reactor install upon module import
@@ -120,24 +123,10 @@ class WebSocketServerFactory(protocol.WebSocketServerFactory, twisted.internet.p
return self.reactor.callLater(delay, fun)
#protocol = WebSocketServerProtocol
# def __init__(self, reactor = None):
# ## lazy import to avoid reactor install upon module import
# if reactor is None:
# from twisted.internet import reactor
# self._reactor = reactor
# def buildProtocol(self, addr):
# proto = self.protocol()
# proto.factory = self
# return proto
class WebSocketClientProtocol(protocol.WebSocketClientProtocol, twisted.internet.protocol.Protocol):
"""
Base class for Twisted WebSocket client protocols.
"""
def connectionMade(self):
@@ -184,12 +173,11 @@ class WebSocketClientProtocol(protocol.WebSocketClientProtocol, twisted.internet
class WebSocketClientFactory(protocol.WebSocketClientFactory, twisted.internet.protocol.ClientFactory):
"""
Base class for Twisted WebSocket client factories.
"""
def __init__(self, *args, **kwargs):
#twisted.internet.protocol.ClientFactory.__init__(self)
protocol.WebSocketClientFactory.__init__(self, *args, **kwargs)
## lazy import to avoid reactor install upon module import

View File

@@ -0,0 +1,233 @@
###############################################################################
##
## Copyright (C) 2011-2013 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
##
## HTTP Status Codes
##
## Source: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
## Adapted on 2011/10/11
##
##
## 1xx Informational
##
## Request received, continuing process.
##
## This class of status code indicates a provisional response, consisting only of
## the Status-Line and optional headers, and is terminated by an empty line.
## Since HTTP/1.0 did not define any 1xx status codes, servers must not send
## a 1xx response to an HTTP/1.0 client except under experimental conditions.
##
CONTINUE = (100, "Continue",
"This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request[2] and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).")
SWITCHING_PROTOCOLS = (101, "Switching Protocols",
"This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.")
PROCESSING = (102, "Processing (WebDAV) (RFC 2518)",
"As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[3] This prevents the client from timing out and assuming the request was lost.")
CHECKPOINT = (103, "Checkpoint",
"This code is used in the Resumable HTTP Requests Proposal to resume aborted PUT or POST requests.")
REQUEST_URI_TOO_LONG = (122, "Request-URI too long",
"This is a non-standard IE7-only code which means the URI is longer than a maximum of 2083 characters.[5][6] (See code 414.)")
##
## 2xx Success
##
## This class of status codes indicates the action requested by the client was
## received, understood, accepted and processed successfully.
##
OK = (200, "OK",
"Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.")
CREATED = (201, "Created",
"The request has been fulfilled and resulted in a new resource being created.")
ACCEPTED = (202, "Accepted",
"The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.")
NON_AUTHORATIVE = (203, "Non-Authoritative Information (since HTTP/1.1)",
"The server successfully processed the request, but is returning information that may be from another source.")
NO_CONTENT = (204, "No Content",
"The server successfully processed the request, but is not returning any content.")
RESET_CONTENT = (205, "Reset Content",
"The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.")
PARTIAL_CONTENT = (206, "Partial Content",
"The server is delivering only part of the resource due to a range header sent by the client. The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.")
MULTI_STATUS = (207, "Multi-Status (WebDAV) (RFC 4918)",
"The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.")
IM_USED = (226, "IM Used (RFC 3229)",
"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.")
##
## 3xx Redirection
##
## The client must take additional action to complete the request.
##
## This class of status code indicates that further action needs to be taken
## by the user agent in order to fulfil the request. The action required may
## be carried out by the user agent without interaction with the user if and
## only if the method used in the second request is GET or HEAD. A user agent
## should not automatically redirect a request more than five times, since such
## redirections usually indicate an infinite loop.
##
MULTIPLE_CHOICES = (300, "Multiple Choices",
"Indicates multiple options for the resource that the client may follow. It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.")
MOVED_PERMANENTLY = (301, "Moved Permanently",
"This and all future requests should be directed to the given URI.")
FOUND = (302, "Found",
"This is an example of industrial practice contradicting the standard. HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was 'Moved Temporarily', but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours. However, some Web applications and frameworks use the 302 status code as if it were the 303.")
SEE_OTHER = (303, "See Other (since HTTP/1.1)",
"The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.")
NOT_MODIFIED = (304, "Not Modified",
"Indicates the resource has not been modified since last requested.[2] Typically, the HTTP client provides a header like the If-Modified-Since header to provide a time against which to compare. Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.")
USE_PROXY = (305, "Use Proxy (since HTTP/1.1)",
"Many HTTP clients (such as Mozilla[11] and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.")
SWITCH_PROXY = (306, "Switch Proxy",
"No longer used. Originally meant 'Subsequent requests should use the specified proxy'.")
TEMPORARY_REDIRECT = (307, "Temporary Redirect (since HTTP/1.1)",
"In this occasion, the request should be repeated with another URI, but future requests can still use the original URI.[2] In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.")
RESUME_INCOMPLETE = (308, "Resume Incomplete",
"This code is used in the Resumable HTTP Requests Proposal to resume aborted PUT or POST requests.")
##
## 4xx Client Error
##
## The 4xx class of status code is intended for cases in which the client
## seems to have erred. Except when responding to a HEAD request, the server
## should include an entity containing an explanation of the error situation,
## and whether it is a temporary or permanent condition. These status codes are
## applicable to any request method. User agents should display any included
## entity to the user. These are typically the most common error codes
## encountered while online.
##
BAD_REQUEST = (400, "Bad Request",
"The request cannot be fulfilled due to bad syntax.")
UNAUTHORIZED = (401, "Unauthorized",
"Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.[2] The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.")
PAYMENT_REQUIRED = (402, "Payment Required",
"Reserved for future use.[2] The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, but that has not happened, and this code is not usually used. As an example of its use, however, Apple's MobileMe service generates a 402 error if the MobileMe account is delinquent.")
FORBIDDEN = (403, "Forbidden",
"The request was a legal request, but the server is refusing to respond to it.[2] Unlike a 401 Unauthorized response, authenticating will make no difference.[2]")
NOT_FOUND = (404, "Not Found",
"The requested resource could not be found but may be available again in the future.[2] Subsequent requests by the client are permissible.")
METHOD_NOT_ALLOWED = (405, "Method Not Allowed",
"A request was made of a resource using a request method not supported by that resource;[2] for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.")
NOT_ACCEPTABLE = (406, "Not Acceptable",
"The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.")
PROXY_AUTH_REQUIRED = (407, "Proxy Authentication Required",
"The client must first authenticate itself with the proxy.")
REQUEST_TIMEOUT = (408, "Request Timeout",
"The server timed out waiting for the request. According to W3 HTTP specifications: 'The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.'")
CONFLICT = (409, "Conflict",
"Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.")
GONE = (410, "Gone",
"Indicates that the resource requested is no longer available and will not be available again.[2] This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. Clients such as search engines should remove the resource from their indices. Most use cases do not require clients and search engines to purge the resource, and a '404 Not Found' may be used instead.")
LENGTH_REQUIRED = (411, "Length Required",
"The request did not specify the length of its content, which is required by the requested resource.")
PRECONDITION_FAILED = (412, "Precondition Failed",
"The server does not meet one of the preconditions that the requester put on the request.")
REQUEST_ENTITY_TOO_LARGE = (413, "Request Entity Too Large",
"The request is larger than the server is willing or able to process.")
REQUEST_URI_TOO_LARGE = (414, "Request-URI Too Long",
"The URI provided was too long for the server to process.")
UNSUPPORTED_MEDIA_TYPE = (415, "Unsupported Media Type",
"The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.")
INVALID_REQUEST_RANGE = (416, "Requested Range Not Satisfiable",
"The client has asked for a portion of the file, but the server cannot supply that portion.[2] For example, if the client asked for a part of the file that lies beyond the end of the file.")
EXPECTATION_FAILED = (417, "Expectation Failed",
"The server cannot meet the requirements of the Expect request-header field.")
TEAPOT = (418, "I'm a teapot (RFC 2324)",
"This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers.")
UNPROCESSABLE_ENTITY = (422, "Unprocessable Entity (WebDAV) (RFC 4918)",
"The request was well-formed but was unable to be followed due to semantic errors.")
LOCKED = (423, "Locked (WebDAV) (RFC 4918)",
"The resource that is being accessed is locked.")
FAILED_DEPENDENCY = (424, "Failed Dependency (WebDAV) (RFC 4918)",
"The request failed due to failure of a previous request (e.g. a PROPPATCH).")
UNORDERED_COLLECTION = (425, "Unordered Collection (RFC 3648)",
"Defined in drafts of 'WebDAV Advanced Collections Protocol', but not present in 'Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol'.")
UPGRADE_REQUIRED = (426, "Upgrade Required (RFC 2817)",
"The client should switch to a different protocol such as TLS/1.0.")
NO_RESPONSE = (444, "No Response",
"A Nginx HTTP server extension. The server returns no information to the client and closes the connection (useful as a deterrent for malware).")
RETRY_WITH = (449, "Retry With",
"A Microsoft extension. The request should be retried after performing the appropriate action.")
PARANTAL_BLOCKED = (450, "Blocked by Windows Parental Controls",
"A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.")
CLIENT_CLOSED_REQUEST = (499, "Client Closed Request",
"An Nginx HTTP server extension. This code is introduced to log the case when the connection is closed by client while HTTP server is processing its request, making server unable to send the HTTP header back.")
##
## 5xx Server Error
##
## The server failed to fulfill an apparently valid request.
##
## Response status codes beginning with the digit "5" indicate cases in which
## the server is aware that it has encountered an error or is otherwise incapable
## of performing the request. Except when responding to a HEAD request, the server
## should include an entity containing an explanation of the error situation, and
## indicate whether it is a temporary or permanent condition. Likewise, user agents
## should display any included entity to the user. These response codes are
## applicable to any request method.
##
INTERNAL_SERVER_ERROR = (500, "Internal Server Error",
"A generic error message, given when no more specific message is suitable.")
NOT_IMPLEMENTED = (501, "Not Implemented",
"The server either does not recognise the request method, or it lacks the ability to fulfill the request.")
BAD_GATEWAY = (502, "Bad Gateway",
"The server was acting as a gateway or proxy and received an invalid response from the upstream server.")
SERVICE_UNAVAILABLE = (503, "Service Unavailable",
"The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.")
GATEWAY_TIMEOUT = (504, "Gateway Timeout",
"The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.")
UNSUPPORTED_HTTP_VERSION = (505, "HTTP Version Not Supported",
"The server does not support the HTTP protocol version used in the request.")
VARIANT_ALSO_NEGOTIATES = (506, "Variant Also Negotiates (RFC 2295)",
"Transparent content negotiation for the request results in a circular reference.")
INSUFFICIENT_STORAGE = (507, "Insufficient Storage (WebDAV)(RFC 4918)",
"The server is unable to store the representation needed to complete the request.")
BANDWIDTH_LIMIT_EXCEEDED = (509, "Bandwidth Limit Exceeded (Apache bw/limited extension)",
"This status code, while used by many servers, is not specified in any RFCs.")
NOT_EXTENDED = (510, "Not Extended (RFC 2774)",
"Further extensions to the request are required for the server to fulfill it.")
NETWORK_READ_TIMEOUT = (598, "Network read timeout error (Informal convention)",
"This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.")
NETWORK_CONNECT_TIMEOUT = (599, "Network connect timeout error (Informal convention)",
"This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.")
class HttpException(Exception):
"""
Throw an instance of this class to deny a WebSocket connection
during handshake in :meth:`autobahn.websocket.WebSocketServerProtocol.onConnect`.
"""
def __init__(self, code, reason):
"""
Constructor.
:param code: HTTP error code.
:type code: int
:param reason: HTTP error reason.
:type reason: str
"""
self.code = code
self.reason = reason

View File

@@ -1,271 +0,0 @@
###############################################################################
##
## Copyright 201-2013 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
##
## HTTP Status Codes
##
## Source: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
## Adapted on 2011/10/11
##
##
## 1xx Informational
##
## Request received, continuing process.
##
## This class of status code indicates a provisional response, consisting only of
## the Status-Line and optional headers, and is terminated by an empty line.
## Since HTTP/1.0 did not define any 1xx status codes, servers must not send
## a 1xx response to an HTTP/1.0 client except under experimental conditions.
##
HTTP_STATUS_CODE_CONTINUE = (100, "Continue",
"This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request[2] and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).")
HTTP_STATUS_CODE_SWITCHING_PROTOCOLS = (101, "Switching Protocols",
"This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.")
HTTP_STATUS_CODE_PROCESSING = (102, "Processing (WebDAV) (RFC 2518)",
"As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[3] This prevents the client from timing out and assuming the request was lost.")
HTTP_STATUS_CODE_CHECKPOINT = (103, "Checkpoint",
"This code is used in the Resumable HTTP Requests Proposal to resume aborted PUT or POST requests.")
HTTP_STATUS_CODE_REQUEST_URI_TOO_LONG = (122, "Request-URI too long",
"This is a non-standard IE7-only code which means the URI is longer than a maximum of 2083 characters.[5][6] (See code 414.)")
##
## 2xx Success
##
## This class of status codes indicates the action requested by the client was
## received, understood, accepted and processed successfully.
##
HTTP_STATUS_CODE_OK = (200, "OK",
"Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.")
HTTP_STATUS_CODE_CREATED = (201, "Created",
"The request has been fulfilled and resulted in a new resource being created.")
HTTP_STATUS_CODE_ACCEPTED = (202, "Accepted",
"The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.")
HTTP_STATUS_CODE_NON_AUTHORATIVE = (203, "Non-Authoritative Information (since HTTP/1.1)",
"The server successfully processed the request, but is returning information that may be from another source.")
HTTP_STATUS_CODE_NO_CONTENT = (204, "No Content",
"The server successfully processed the request, but is not returning any content.")
HTTP_STATUS_CODE_RESET_CONTENT = (205, "Reset Content",
"The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.")
HTTP_STATUS_CODE_PARTIAL_CONTENT = (206, "Partial Content",
"The server is delivering only part of the resource due to a range header sent by the client. The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.")
HTTP_STATUS_CODE_MULTI_STATUS = (207, "Multi-Status (WebDAV) (RFC 4918)",
"The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.")
HTTP_STATUS_CODE_IM_USED = (226, "IM Used (RFC 3229)",
"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.")
##
## 3xx Redirection
##
## The client must take additional action to complete the request.
##
## This class of status code indicates that further action needs to be taken
## by the user agent in order to fulfil the request. The action required may
## be carried out by the user agent without interaction with the user if and
## only if the method used in the second request is GET or HEAD. A user agent
## should not automatically redirect a request more than five times, since such
## redirections usually indicate an infinite loop.
##
HTTP_STATUS_CODE_MULTIPLE_CHOICES = (300, "Multiple Choices",
"Indicates multiple options for the resource that the client may follow. It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.")
HTTP_STATUS_CODE_MOVED_PERMANENTLY = (301, "Moved Permanently",
"This and all future requests should be directed to the given URI.")
HTTP_STATUS_CODE_FOUND = (302, "Found",
"This is an example of industrial practice contradicting the standard. HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was 'Moved Temporarily', but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours. However, some Web applications and frameworks use the 302 status code as if it were the 303.")
HTTP_STATUS_CODE_SEE_OTHER = (303, "See Other (since HTTP/1.1)",
"The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.")
HTTP_STATUS_CODE_NOT_MODIFIED = (304, "Not Modified",
"Indicates the resource has not been modified since last requested.[2] Typically, the HTTP client provides a header like the If-Modified-Since header to provide a time against which to compare. Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.")
HTTP_STATUS_CODE_USE_PROXY = (305, "Use Proxy (since HTTP/1.1)",
"Many HTTP clients (such as Mozilla[11] and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.")
HTTP_STATUS_CODE_SWITCH_PROXY = (306, "Switch Proxy",
"No longer used. Originally meant 'Subsequent requests should use the specified proxy'.")
HTTP_STATUS_CODE_TEMPORARY_REDIRECT = (307, "Temporary Redirect (since HTTP/1.1)",
"In this occasion, the request should be repeated with another URI, but future requests can still use the original URI.[2] In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.")
HTTP_STATUS_CODE_RESUME_INCOMPLETE = (308, "Resume Incomplete",
"This code is used in the Resumable HTTP Requests Proposal to resume aborted PUT or POST requests.")
##
## 4xx Client Error
##
## The 4xx class of status code is intended for cases in which the client
## seems to have erred. Except when responding to a HEAD request, the server
## should include an entity containing an explanation of the error situation,
## and whether it is a temporary or permanent condition. These status codes are
## applicable to any request method. User agents should display any included
## entity to the user. These are typically the most common error codes
## encountered while online.
##
HTTP_STATUS_CODE_BAD_REQUEST = (400, "Bad Request",
"The request cannot be fulfilled due to bad syntax.")
HTTP_STATUS_CODE_UNAUTHORIZED = (401, "Unauthorized",
"Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.[2] The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.")
HTTP_STATUS_CODE_PAYMENT_REQUIRED = (402, "Payment Required",
"Reserved for future use.[2] The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, but that has not happened, and this code is not usually used. As an example of its use, however, Apple's MobileMe service generates a 402 error if the MobileMe account is delinquent.")
HTTP_STATUS_CODE_FORBIDDEN = (403, "Forbidden",
"The request was a legal request, but the server is refusing to respond to it.[2] Unlike a 401 Unauthorized response, authenticating will make no difference.[2]")
HTTP_STATUS_CODE_NOT_FOUND = (404, "Not Found",
"The requested resource could not be found but may be available again in the future.[2] Subsequent requests by the client are permissible.")
HTTP_STATUS_CODE_METHOD_NOT_ALLOWED = (405, "Method Not Allowed",
"A request was made of a resource using a request method not supported by that resource;[2] for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.")
HTTP_STATUS_CODE_NOT_ACCEPTABLE = (406, "Not Acceptable",
"The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.")
HTTP_STATUS_CODE_PROXY_AUTH_REQUIRED = (407, "Proxy Authentication Required",
"The client must first authenticate itself with the proxy.")
HTTP_STATUS_CODE_REQUEST_TIMEOUT = (408, "Request Timeout",
"The server timed out waiting for the request. According to W3 HTTP specifications: 'The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.'")
HTTP_STATUS_CODE_CONFLICT = (409, "Conflict",
"Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.")
HTTP_STATUS_CODE_GONE = (410, "Gone",
"Indicates that the resource requested is no longer available and will not be available again.[2] This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. Clients such as search engines should remove the resource from their indices. Most use cases do not require clients and search engines to purge the resource, and a '404 Not Found' may be used instead.")
HTTP_STATUS_CODE_LENGTH_REQUIRED = (411, "Length Required",
"The request did not specify the length of its content, which is required by the requested resource.")
HTTP_STATUS_CODE_PRECONDITION_FAILED = (412, "Precondition Failed",
"The server does not meet one of the preconditions that the requester put on the request.")
HTTP_STATUS_CODE_REQUEST_ENTITY_TOO_LARGE = (413, "Request Entity Too Large",
"The request is larger than the server is willing or able to process.")
HTTP_STATUS_CODE_REQUEST_URI_TOO_LARGE = (414, "Request-URI Too Long",
"The URI provided was too long for the server to process.")
HTTP_STATUS_CODE_UNSUPPORTED_MEDIA_TYPE = (415, "Unsupported Media Type",
"The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.")
HTTP_STATUS_CODE_INVALID_REQUEST_RANGE = (416, "Requested Range Not Satisfiable",
"The client has asked for a portion of the file, but the server cannot supply that portion.[2] For example, if the client asked for a part of the file that lies beyond the end of the file.")
HTTP_STATUS_CODE_EXPECTATION_FAILED = (417, "Expectation Failed",
"The server cannot meet the requirements of the Expect request-header field.")
HTTP_STATUS_CODE_TEAPOT = (418, "I'm a teapot (RFC 2324)",
"This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers.")
HTTP_STATUS_CODE_UNPROCESSABLE_ENTITY = (422, "Unprocessable Entity (WebDAV) (RFC 4918)",
"The request was well-formed but was unable to be followed due to semantic errors.")
HTTP_STATUS_CODE_LOCKED = (423, "Locked (WebDAV) (RFC 4918)",
"The resource that is being accessed is locked.")
HTTP_STATUS_CODE_FAILED_DEPENDENCY = (424, "Failed Dependency (WebDAV) (RFC 4918)",
"The request failed due to failure of a previous request (e.g. a PROPPATCH).")
HTTP_STATUS_CODE_UNORDERED_COLLECTION = (425, "Unordered Collection (RFC 3648)",
"Defined in drafts of 'WebDAV Advanced Collections Protocol', but not present in 'Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol'.")
HTTP_STATUS_CODE_UPGRADE_REQUIRED = (426, "Upgrade Required (RFC 2817)",
"The client should switch to a different protocol such as TLS/1.0.")
HTTP_STATUS_CODE_NO_RESPONSE = (444, "No Response",
"A Nginx HTTP server extension. The server returns no information to the client and closes the connection (useful as a deterrent for malware).")
HTTP_STATUS_CODE_RETRY_WITH = (449, "Retry With",
"A Microsoft extension. The request should be retried after performing the appropriate action.")
HTTP_STATUS_CODE_PARANTAL_BLOCKED = (450, "Blocked by Windows Parental Controls",
"A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.")
HTTP_STATUS_CODE_CLIENT_CLOSED_REQUEST = (499, "Client Closed Request",
"An Nginx HTTP server extension. This code is introduced to log the case when the connection is closed by client while HTTP server is processing its request, making server unable to send the HTTP header back.")
##
## 5xx Server Error
##
## The server failed to fulfill an apparently valid request.
##
## Response status codes beginning with the digit "5" indicate cases in which
## the server is aware that it has encountered an error or is otherwise incapable
## of performing the request. Except when responding to a HEAD request, the server
## should include an entity containing an explanation of the error situation, and
## indicate whether it is a temporary or permanent condition. Likewise, user agents
## should display any included entity to the user. These response codes are
## applicable to any request method.
##
HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR = (500, "Internal Server Error",
"A generic error message, given when no more specific message is suitable.")
HTTP_STATUS_CODE_NOT_IMPLEMENTED = (501, "Not Implemented",
"The server either does not recognise the request method, or it lacks the ability to fulfill the request.")
HTTP_STATUS_CODE_BAD_GATEWAY = (502, "Bad Gateway",
"The server was acting as a gateway or proxy and received an invalid response from the upstream server.")
HTTP_STATUS_CODE_SERVICE_UNAVAILABLE = (503, "Service Unavailable",
"The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.")
HTTP_STATUS_CODE_GATEWAY_TIMEOUT = (504, "Gateway Timeout",
"The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.")
HTTP_STATUS_CODE_UNSUPPORTED_HTTP_VERSION = (505, "HTTP Version Not Supported",
"The server does not support the HTTP protocol version used in the request.")
HTTP_STATUS_CODE_VARIANT_ALSO_NEGOTIATES = (506, "Variant Also Negotiates (RFC 2295)",
"Transparent content negotiation for the request results in a circular reference.")
HTTP_STATUS_CODE_INSUFFICIENT_STORAGE = (507, "Insufficient Storage (WebDAV)(RFC 4918)",
"The server is unable to store the representation needed to complete the request.")
HTTP_STATUS_CODE_BANDWIDTH_LIMIT_EXCEEDED = (509, "Bandwidth Limit Exceeded (Apache bw/limited extension)",
"This status code, while used by many servers, is not specified in any RFCs.")
HTTP_STATUS_CODE_NOT_EXTENDED = (510, "Not Extended (RFC 2774)",
"Further extensions to the request are required for the server to fulfill it.")
HTTP_STATUS_CODE_NETWORK_READ_TIMEOUT = (598, "Network read timeout error (Informal convention)",
"This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.")
HTTP_STATUS_CODE_NETWORK_CONNECT_TIMEOUT = (599, "Network connect timeout error (Informal convention)",
"This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.")

View File

@@ -24,7 +24,6 @@ PY3 = sys.version_info.major > 2
__all__ = ["createWsUrl",
"parseWsUrl",
"HttpException",
"ConnectionRequest",
"ConnectionResponse",
"Timings",
@@ -77,8 +76,8 @@ from autobahn.interfaces import IWebSocketChannel, \
from autobahn.util import Stopwatch
from autobahn.websocket.utf8validator import Utf8Validator
from autobahn.websocket.xormasker import XorMaskerNull, createXorMasker
from autobahn.websocket.httpstatus import *
from autobahn.websocket.compress import *
from autobahn.websocket import http
def createWsUrl(hostname, port = None, isSecure = False, path = None, params = None):
@@ -272,27 +271,6 @@ class FrameHeader:
class HttpException:
"""
Throw an instance of this class to deny a WebSocket connection
during handshake in :meth:`autobahn.websocket.WebSocketServerProtocol.onConnect`.
You can find definitions of HTTP status codes in module :mod:`autobahn.httpstatus`.
"""
def __init__(self, code, reason):
"""
Constructor.
:param code: HTTP error code.
:type code: int
:param reason: HTTP error reason.
:type reason: str
"""
self.code = code
self.reason = reason
class ConnectionRequest:
"""
Thin-wrapper for WebSocket connection request information
@@ -1991,7 +1969,7 @@ class WebSocketProtocol:
Modes: Hybi
"""
payload = ''.join(self.control_frame_data)
payload = b''.join(self.control_frame_data)
self.control_frame_data = None
## CLOSE frame
@@ -2200,7 +2178,7 @@ class WebSocketProtocol:
self.sendData("\xff\x00")
else:
## construct Hybi close frame payload and send frame
payload = ""
payload = b''
if code is not None:
payload += struct.pack("!H", code)
if reasonUtf8 is not None:
@@ -2842,7 +2820,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
Throw HttpException when you don't want to accept the WebSocket
connection request. For example, throw a
`HttpException(httpstatus.HTTP_STATUS_CODE_UNAUTHORIZED[0], "You are not authorized for this!")`.
`HttpException(httpstatus.http.UNAUTHORIZED[0], "You are not authorized for this!")`.
When you want to accept the connection, return the accepted protocol
from list of WebSocket (sub)protocols provided by client or None to
@@ -2922,10 +2900,10 @@ class WebSocketServerProtocol(WebSocketProtocol):
if len(rl) != 3:
return self.failHandshake("Bad HTTP request status line '%s'" % self.http_status_line)
if rl[0].strip() != "GET":
return self.failHandshake("HTTP method '%s' not allowed" % rl[0], HTTP_STATUS_CODE_METHOD_NOT_ALLOWED[0])
return self.failHandshake("HTTP method '%s' not allowed" % rl[0], http.METHOD_NOT_ALLOWED[0])
vs = rl[2].strip().split("/")
if len(vs) != 2 or vs[0] != "HTTP" or vs[1] not in ["1.1"]:
return self.failHandshake("Unsupported HTTP version '%s'" % rl[2], HTTP_STATUS_CODE_UNSUPPORTED_HTTP_VERSION[0])
return self.failHandshake("Unsupported HTTP version '%s'" % rl[2], http.UNSUPPORTED_HTTP_VERSION[0])
## HTTP Request line : REQUEST-URI
##
@@ -3009,7 +2987,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
self.dropConnection(abort = False)
return
else:
return self.failHandshake("HTTP Upgrade header missing", HTTP_STATUS_CODE_UPGRADE_REQUIRED[0])
return self.failHandshake("HTTP Upgrade header missing", http.UPGRADE_REQUIRED[0])
upgradeWebSocket = False
for u in self.http_headers["upgrade"].split(","):
if u.strip().lower() == "websocket":
@@ -3057,7 +3035,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
sv.reverse()
svs = ','.join([str(x) for x in sv])
return self.failHandshake("WebSocket version %d not supported (supported versions: %s)" % (version, svs),
HTTP_STATUS_CODE_BAD_REQUEST[0],
http.BAD_REQUEST[0],
[("Sec-WebSocket-Version", svs)])
else:
## store the protocol version we are supposed to talk
@@ -3181,13 +3159,18 @@ class WebSocketServerProtocol(WebSocketProtocol):
self.websocket_protocols,
self.websocket_extensions)
self._run_onConnect(self.connectionRequest)
print("1"*10)
self._onConnect(self.connectionRequest)
#yield from self._onConnect(self.connectionRequest)
print("2"*10)
def _processHandshake_buildResponse(self, res):
def succeedHandshake(self, res):
"""
Callback for Deferred returned by self.onConnect. Generates the response for the handshake.
Callback after onConnect() returns successfully. Generates the response for the handshake.
"""
print("0"*10)
print(res)
protocol = None
headers = {}
if type(res) == tuple:
@@ -3258,7 +3241,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
## build response to complete WebSocket handshake
##
response = "HTTP/1.1 %d Switching Protocols\x0d\x0a" % HTTP_STATUS_CODE_SWITCHING_PROTOCOLS[0]
response = "HTTP/1.1 %d Switching Protocols\x0d\x0a" % http.SWITCHING_PROTOCOLS[0]
if self.factory.server is not None and self.factory.server != "":
response += "Server: %s\x0d\x0a" % self.factory.server
@@ -3315,8 +3298,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
## compute accept body
##
accept_val = struct.pack(">II", key1, key2) + key3
accept = hashlib.md5(accept_val).digest()
response_body = accept
response_body = hashlib.md5(accept_val).digest()
else:
## compute Sec-WebSocket-Accept
@@ -3334,15 +3316,18 @@ class WebSocketServerProtocol(WebSocketProtocol):
## end of HTTP response headers
response += "\x0d\x0a"
response_body = b''
response_body = None
if self.debug:
self.factory._log("sending HTTP response:\n\n%s%s\n\n" % (response, binascii.b2a_hex(response_body)))
## save and send out opening HS data
## send out opening handshake response
##
self.http_response_data = response.encode('utf8') + response_body
self.sendData(self.http_response_data)
if self.debug:
self.factory._log("sending HTTP response:\n\n%s" % response)
self.sendData(response.encode('utf8'))
if response_body:
if self.debug:
self.factory._log("sending HTTP response body:\n\n%s" % binascii.b2a_hex(response_body))
self.sendData(response_body)
## opening handshake completed, move WebSocket connection into OPEN state
##
@@ -3374,20 +3359,7 @@ class WebSocketServerProtocol(WebSocketProtocol):
self.consumeData()
def _processHandshake_failed(self, failure):
"""
Errback for Deferred returned by self.onConnect. Generates a HTTP error response for the handshake.
"""
e = failure.value
if failure.check(HttpException):
return self.failHandshake(e.reason, e.code)
else:
self.factory._log("Exception raised in onConnect() - %s" % str(e))
return self.failHandshake("Internal Server Error", HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR[0])
def failHandshake(self, reason, code = HTTP_STATUS_CODE_BAD_REQUEST[0], responseHeaders = []):
def failHandshake(self, reason, code = http.BAD_REQUEST[0], responseHeaders = []):
"""
During opening handshake the client request was invalid, we send a HTTP
error response and then drop the connection.
@@ -3402,38 +3374,37 @@ class WebSocketServerProtocol(WebSocketProtocol):
"""
Send out HTTP error response.
"""
response = "HTTP/1.1 %d %s\x0d\x0a" % (code, reason.encode("utf-8"))
response = "HTTP/1.1 %d %s\x0d\x0a" % (code, reason)
for h in responseHeaders:
response += "%s: %s\x0d\x0a" % (h[0], h[1].encode("utf-8"))
response += "%s: %s\x0d\x0a" % (h[0], h[1])
response += "\x0d\x0a"
self.sendData(response)
self.sendData(response.encode('utf8'))
def sendHtml(self, html):
"""
Send HTML page HTTP response.
"""
raw = html.encode("utf-8")
response = "HTTP/1.1 %d %s\x0d\x0a" % (HTTP_STATUS_CODE_OK[0], HTTP_STATUS_CODE_OK[1])
response = "HTTP/1.1 %d %s\x0d\x0a" % (http.OK[0], http.OK[1])
if self.factory.server is not None and self.factory.server != "":
response += "Server: %s\x0d\x0a" % self.factory.server.encode("utf-8")
response += "Server: %s\x0d\x0a" % self.factory.server
response += "Content-Type: text/html; charset=UTF-8\x0d\x0a"
response += "Content-Length: %d\x0d\x0a" % len(raw)
response += "\x0d\x0a"
response += raw
self.sendData(response)
self.sendData(response.encode('utf8'))
self.sendData(html.encode('utf8'))
def sendRedirect(self, url):
"""
Send HTTP Redirect (303) response.
"""
response = "HTTP/1.1 %d\x0d\x0a" % HTTP_STATUS_CODE_SEE_OTHER[0]
#if self.factory.server is not None and self.factory.server != "":
# response += "Server: %s\x0d\x0a" % self.factory.server.encode("utf-8")
response += "Location: %s\x0d\x0a" % url.encode("utf-8")
response = "HTTP/1.1 %d\x0d\x0a" % http.SEE_OTHER[0]
if self.factory.server is not None and self.factory.server != "":
response += "Server: %s\x0d\x0a" % self.factory.server
response += "Location: %s\x0d\x0a" % url
response += "\x0d\x0a"
self.sendData(response)
self.sendData(response.encode('utf8'))
def sendServerStatus(self, redirectUrl = None, redirectAfter = 0):
@@ -3930,12 +3901,12 @@ class WebSocketClientProtocol(WebSocketProtocol):
## construct WS opening handshake HTTP header
##
request = "GET %s HTTP/1.1\x0d\x0a" % self.factory.resource.encode("utf-8")
request = "GET %s HTTP/1.1\x0d\x0a" % self.factory.resource
if self.factory.useragent is not None and self.factory.useragent != "":
request += "User-Agent: %s\x0d\x0a" % self.factory.useragent.encode("utf-8")
request += "User-Agent: %s\x0d\x0a" % self.factory.useragent
request += "Host: %s:%d\x0d\x0a" % (self.factory.host.encode("utf-8"), self.factory.port)
request += "Host: %s:%d\x0d\x0a" % (self.factory.host, self.factory.port)
request += "Upgrade: WebSocket\x0d\x0a"
request += "Connection: Upgrade\x0d\x0a"
@@ -3951,7 +3922,7 @@ class WebSocketClientProtocol(WebSocketProtocol):
## optional, user supplied additional HTTP headers
##
for uh in self.factory.headers.items():
request += "%s: %s\x0d\x0a" % (uh[0].encode("utf-8"), uh[1].encode("utf-8"))
request += "%s: %s\x0d\x0a" % (uh[0], uh[1])
## handshake random key
##
@@ -3970,17 +3941,19 @@ class WebSocketClientProtocol(WebSocketProtocol):
## First two keys.
request += "Sec-WebSocket-Key1: %s\x0d\x0a" % self.websocket_key1
request += "Sec-WebSocket-Key2: %s\x0d\x0a" % self.websocket_key2
else:
request_body = self.websocket_key3
else:
self.websocket_key = base64.b64encode(os.urandom(16))
request += "Sec-WebSocket-Key: %s\x0d\x0a" % self.websocket_key
request += "Sec-WebSocket-Key: %s\x0d\x0a" % self.websocket_key.decode()
request_body = None
## optional origin announced
##
if self.factory.origin:
if self.version > 10 or self.version == 0:
request += "Origin: %s\x0d\x0a" % self.factory.origin.encode("utf-8")
request += "Origin: %s\x0d\x0a" % self.factory.origin
else:
request += "Sec-WebSocket-Origin: %s\x0d\x0a" % self.factory.origin.encode("utf-8")
request += "Sec-WebSocket-Origin: %s\x0d\x0a" % self.factory.origin
## optional list of WS subprotocols announced
##
@@ -4007,16 +3980,13 @@ class WebSocketClientProtocol(WebSocketProtocol):
request += "\x0d\x0a"
if self.version == 0:
self.sendData(request.encode('utf8'))
if request_body:
## Write HTTP request body for Hixie-76
request += self.websocket_key3
self.http_request_data = request
self.sendData(request_body)
if self.debug:
self.factory._log(self.http_request_data)
self.sendData(self.http_request_data)
self.factory._log(request)
def processHandshake(self):
@@ -4025,7 +3995,7 @@ class WebSocketClientProtocol(WebSocketProtocol):
"""
## only proceed when we have fully received the HTTP request line and all headers
##
end_of_header = self.data.find("\x0d\x0a\x0d\x0a")
end_of_header = self.data.find(b"\x0d\x0a\x0d\x0a")
if end_of_header >= 0:
self.http_response_data = self.data[:end_of_header + 4]
@@ -4060,7 +4030,7 @@ class WebSocketClientProtocol(WebSocketProtocol):
status_code = int(sl[1].strip())
except:
return self.failHandshake("Bad HTTP status code ('%s')" % sl[1].strip())
if status_code != HTTP_STATUS_CODE_SWITCHING_PROTOCOLS[0]:
if status_code != http.SWITCHING_PROTOCOLS[0]:
## FIXME: handle redirects
## FIXME: handle authentication required
@@ -4102,7 +4072,7 @@ class WebSocketClientProtocol(WebSocketProtocol):
sha1 = hashlib.sha1()
sha1.update(self.websocket_key + WebSocketProtocol._WS_MAGIC)
sec_websocket_accept = base64.b64encode(sha1.digest())
sec_websocket_accept = base64.b64encode(sha1.digest()).decode()
if sec_websocket_accept_got != sec_websocket_accept:
return self.failHandshake("HTTP Sec-WebSocket-Accept bogus value : expected %s / got %s" % (sec_websocket_accept, sec_websocket_accept_got))
@@ -4222,7 +4192,10 @@ class WebSocketClientProtocol(WebSocketProtocol):
##
if self.trackedTimings:
self.trackedTimings.track("onOpen")
self.onOpen()
print("X"*100)
yield from self.onOpen()
print("Y"*100)
## process rest, if any
##

View File

@@ -1,2 +1,5 @@
server:
PYTHONPATH=../../../../autobahn python3 server.py
client:
PYTHONPATH=../../../../autobahn python3 client.py

View File

@@ -0,0 +1,65 @@
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var socket = null;
var isopen = false;
window.onload = function() {
socket = new WebSocket("ws://127.0.0.1:9000");
socket.binaryType = "arraybuffer";
socket.onopen = function() {
console.log("Connected!");
isopen = true;
}
socket.onmessage = function(e) {
if (typeof e.data == "string") {
console.log("Text message received: " + e.data);
} else {
var arr = new Uint8Array(e.data);
var hex = '';
for (var i = 0; i < arr.length; i++) {
hex += ('00' + arr[i].toString(16)).substr(-2);
}
console.log("Binary message received: " + hex);
}
}
socket.onclose = function(e) {
console.log("Connection closed.");
socket = null;
isopen = false;
}
};
function sendText() {
if (isopen) {
socket.send("Hello, world!");
console.log("Text message sent.");
} else {
console.log("Connection not opened.")
}
};
function sendBinary() {
if (isopen) {
var buf = new ArrayBuffer(32);
var arr = new Uint8Array(buf);
for (i = 0; i < arr.length; ++i) arr[i] = i;
socket.send(buf);
console.log("Binary message sent.");
} else {
console.log("Connection not opened.")
}
};
</script>
</head>
<body>
<p>Open your browser's JavaScript console to see what's happening (hit F12).</p>
<button onclick='sendText();'>Send Text Message</button>
<button onclick='sendBinary();'>Send Binary Message</button>
</body>
</html>

View File

@@ -0,0 +1,79 @@
###############################################################################
##
## Copyright (C) 2013 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
from autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
import asyncio
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {}".format(response.peer))
@asyncio.coroutine
def slow_sqrt_coroutine(self, x):
yield from asyncio.sleep(1)
if x >= 0:
return math.sqrt(x)
else:
raise Exception("negative number")
def onOpen(self):
print("WebSocket connection open.")
value = yield from self.slow_sqrt_coroutine(2)
#value = 2.1
msg = "result = {}".format(value)
self.sendMessage(msg.encode('utf8'))
def onOpen2(self):
print("WebSocket connection open.")
def hello():
self.sendMessage(u"Hello, world!".encode('utf8'))
self.sendMessage(b"\x00\x01\x03\x04", binary = True)
self.factory.loop.call_later(1, hello)
## start sending messages every second ..
hello()
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {} bytes".format(len(payload)))
else:
print("Text message received: {}".format(payload.decode('utf8')))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {}".format(reason))
if __name__ == '__main__':
import asyncio
factory = WebSocketClientFactory("ws://localhost:9000", debug = True)
factory.protocol = MyClientProtocol
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, '127.0.0.1', 9000)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()

View File

@@ -1,6 +1,6 @@
###############################################################################
##
## Copyright 2013 Tavendo GmbH
## Copyright (C) 2013 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
@@ -20,11 +20,17 @@ from autobahn.asyncio.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
import asyncio
from autobahn.websocket import http
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {}".format(request.peer))
#yield from asyncio.sleep(0.2)
return None
#raise Exception("denied")
#raise http.HttpException(http.UNAUTHORIZED[0], "You are now allowed.")
def onOpen(self):
print("WebSocket connection open.")
@@ -47,7 +53,7 @@ if __name__ == '__main__':
import asyncio
factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
factory = WebSocketServerFactory("ws://localhost:9000", debug = True)
factory.protocol = MyServerProtocol
loop = asyncio.get_event_loop()

View File

@@ -2,32 +2,64 @@
<html>
<head>
<script type="text/javascript">
var sock = null;
var socket = null;
var isopen = false;
window.onload = function() {
sock = new WebSocket("ws://127.0.0.1:9000");
socket = new WebSocket("ws://127.0.0.1:9000");
socket.binaryType = "arraybuffer";
sock.onopen = function() {
socket.onopen = function() {
console.log("Connected!");
isopen = true;
}
sock.onmessage = function(e) {
console.log("Message received: " + e.data);
socket.onmessage = function(e) {
if (typeof e.data == "string") {
console.log("Text message received: " + e.data);
} else {
var arr = new Uint8Array(e.data);
var hex = '';
for (var i = 0; i < arr.length; i++) {
hex += ('00' + arr[i].toString(16)).substr(-2);
}
console.log("Binary message received: " + hex);
}
}
sock.onclose = function(e) {
socket.onclose = function(e) {
console.log("Connection closed.");
socket = null;
isopen = false;
}
};
function send() {
sock.send("Hello, world!");
console.log("Message sent ..");
function sendText() {
if (isopen) {
socket.send("Hello, world!");
console.log("Text message sent.");
} else {
console.log("Connection not opened.")
}
};
function sendBinary() {
if (isopen) {
var buf = new ArrayBuffer(32);
var arr = new Uint8Array(buf);
for (i = 0; i < arr.length; ++i) arr[i] = i;
socket.send(buf);
console.log("Binary message sent.");
} else {
console.log("Connection not opened.")
}
};
</script>
</head>
<body>
<button onclick='send();'>Send Message</button>
<p>Open your browser's JavaScript console to see what's happening (hit F12).</p>
<button onclick='sendText();'>Send Text Message</button>
<button onclick='sendBinary();'>Send Binary Message</button>
</body>
</html>

View File

@@ -18,13 +18,25 @@
from autobahn.twisted.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
from autobahn.websocket import http
from twisted.internet.defer import Deferred
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {}".format(request.peer))
d = Deferred()
def fail():
#raise Exception("denied")
#raise http.HttpException(http.UNAUTHORIZED[0], "You are now allowed.")
#d.errback(http.HttpException(http.UNAUTHORIZED[0], "You are now allowed."))
#d.errback(Exception("denied"))
d.callback(None)
self.factory.reactor.callLater(0.2, fail)
return d
def onOpen(self):
print("WebSocket connection open.")