diff --git a/AUTHORS b/AUTHORS index b1cc15c..c3e2929 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,14 +1,6 @@ This SocketIO server based on Gevent and was written by: - Jeffrey Gelens - -Current Maintainers: + Shuo Li - Alexandre Bourget - John Anderson - -Contributors: - Denis Bilenko - Sébastien Béal - jpellerin (JP) - Philip Neustrom +Based on gevent_socketio created by: + Jeffrey Gelens diff --git a/CHANGELOG b/CHANGELOG deleted file mode 100644 index 9f7abad..0000000 --- a/CHANGELOG +++ /dev/null @@ -1,68 +0,0 @@ -New in 0.3.6 (since 0.3.5-rc3) ------------------------------ - - * initialize() on Namespace objects, as well as Mixins (and all - descendants) is now called by the framework, with ``self`` as a - parameter. - * xhr-longpoll fixed for compat with gevent 1.0bX - * gevent 1.0 bugfixes - * added a paster server integration , use with: egg:gevent-socketio#paster - * Fixed memory leak - -New in 0.3.5-rc3 (since 0.3.5-rc2) ------------------------------ - * Compatibility with gevent 1.0 - * Configurable json serialization - * Django server support - * Better jsonp support - -New in 0.3.5-rc2 (since 0.3.5-rc1) ------------------------------ - * We echo the connect packet back to the client now - * namespace on handler is now called 'resource' to match node.js - * Even better flash policy support, well tested in IE - * Memory Leak Fixes - -New in 0.3.5-rc1 (since 0.3.5-beta) ------------------------------ - * Better test coverage on packets and namespace - * recv_disconnect now works from heartbeats - * ACLs weren't being checked when events fired - * Handle decimals in messages now - * Flash policy server support was improved, now default to port 10843 - -New in 0.3.5-beta (since 0.3) ------------------------------ - -* Official repository now on Github: https://github.com/abourget/gevent-socketio -* Official documentation now on ReadTheDocs: http://readthedocs.org/docs/gevent-socketio/en/latest/ -* Largely improved documentation -* Added tests for packets, namespace and socket -* Added several examples (chatter2, testapp, chatter3, chatter4, cross-origin), fixed up the chat.py example. -* Added the ``initialize()`` method to namespaces. -* Added ``reset_acl()`` on namespaces. -* Renamed ``call_method`` to ``call_method_with_acl`` on namespaces. -* Added a Gunicorn worker (GeventSocketIOWorker) and docs -* Implemented the 'ack' callback functions, on both the Python and Javascript sides (when you emit with a callback function as the last argument in javascript, or with keyword ``callback=function`` in Python). -* Added support for disconnection clean-up (``disconnect()`` on namespaces) -* Added a ``session`` dict to both Socket and Namespace objects (a session is unique to a Socket, but provided on the Namespace for convenience), which can hold any session data. -* Improved the RoomsMixin, changed signature of the "emit_to_room" function. -* Improved the BroadcastMixin, implemented the broadcast_event_not_me() -* Added XHR access control headers on handshake - -The new release is marked as beta, but is still pretty stable and can be used. All the major features are there, but we might want to change some small bits here and there, for clarity or conciseness. - - -New in 0.3 (since previous releases) ------------------------------------- - -* Implemented the Socket.IO 0.7+ protocol. -* Added namespaces and a way to catch events and dispatch them -* Added documentation -* Works on most web frameworks where very small integration is required -* ..woah, so much has changed.. - -Don't use pyramid_socketio anymore, as most of the concepts have been -moved to gevent-socketio. Instead of using the old django-socketio -package with single function dispatchs, use gevent-socketio directly. -See examples and documentation for integration. diff --git a/LICENSE b/LICENSE index 754d5ad..a22a2da 100644 --- a/LICENSE +++ b/LICENSE @@ -1,24 +1 @@ -Copyright (c) 2010, Noppo (Jeffrey Gelens) -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. -Neither the name of the Noppo nor the names of its contributors may be -used to endorse or promote products derived from this software without specific -prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +MIT diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index e98faf5..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,10 +0,0 @@ -include LICENSE -include AUTHORS -include CHANGELOG -include MANIFEST.in -include README.rst -recursive-include socketio *py -exclude socketio/.ropeproject/* -exclude socketio/sample_protocol_for_doc.py -recursive-include docs * -recursive-include tests * diff --git a/NOTES b/NOTES new file mode 100644 index 0000000..2ed5328 --- /dev/null +++ b/NOTES @@ -0,0 +1,25 @@ +old gevent socketio + +xhr polling: + +The loop blocks at socket get_multiple_client_msgs, which call client_queue.get() (it passed a timeout parameter to prevent blocking forever) + + +websocket: + +The handler handle_one_response() waits with gevent.joinall(socket.jobs) + * All jobs spawned for the socket is maintained in socket's jobs array. + (what about the timeout?) + A: The transport send_into_ws do a try except, when a WebSocketError raised, (Fllowing is wrong: it will call socket's disconnect() which kills all jobs) + (Correction: The socket will spawn a watcher, which kills all the jobs and disconnect all namespaces) + The socket has a kill method, which cleaned all resources, all jobs, disconnect all namespaces etc + BUG: The disconnect for the socket not set state as closing or closed + + +socketio_manage has two usages: + * hook up the request from framework to socket + This still valid in GS2, we still need a way to hook the framework's request and pass it to namespaces. + We need to pass the request to framework's application and assign the request to socket. The socket has a context (to distinguish from environ), it holds a value for framework_request. + + * wait on the socket's receiver loop + This is not required since now the main loop waits on response's event, at any point that needs to end the loop, the response's end should be called. diff --git a/README.rst b/README.rst index df21709..667f214 100644 --- a/README.rst +++ b/README.rst @@ -1,70 +1,33 @@ -Presentation +Heads up ============ +This project is deprecated by [gevent_socketio2](https://github.com/shuoli84/gevent_socketio2). -.. image:: https://secure.travis-ci.org/abourget/gevent-socketio.png?branch=master -``gevent-socketio`` is a Python implementation of the Socket.IO -protocol, developed originally for Node.js by LearnBoost and then -ported to other languages. Socket.IO enables real-time web -communications between a browser and a server, using a WebSocket-like -API. One aim of this project is to provide a single ``gevent``-based -API that works across the different WSGI-based web frameworks out -there (Pyramid, Pylons, Flask, web2py, Django, etc...). Only ~3 lines -of code are required to tie-in ``gevent-socketio`` in your framework. -Note: you need to use the ``gevent`` python WSGI server to use -``gevent-socketio``. +Introduction +============ +gevent_socketio2 is socketio 1.0 implementation. It based on gevent_socketio, with lots of modifications in source code to support socketio protocol 1.0. It is under heavy development, production usage is not recommended. Technical overview ================== -Most of the ``gevent-socketio`` implementation is pure Python. There -is an obvious dependency on ``gevent``, and another on -``gevent-websocket``. There are integration examples for Pyramid, Flask, -Django and BYOF (bring your own framework!). +Depends on 'gevent', 'gevent-websocket', 'pybob', 'pyee'. +pybob provides a convinient request response class. +pyee is the EventEmitter for python. Since this is a port from socketio, there is lots logic chained by event and listener. Documentation and References ============================ -You can read the renderered Sphinx docs at: - -* http://readthedocs.org/docs/gevent-socketio/en/latest/ - -Discussion and questions happen on the mailing list: - -* https://groups.google.com/forum/#!forum/gevent-socketio - -or in the Github issue tracking: - -* https://github.com/abourget/gevent-socketio/issues - -You can also contact the maintainer: - -* https://twitter.com/#!/bourgetalexndre -* https://plus.google.com/109333785244622657612 +TBD Installation ============ -You can install with standard Python methods:: +TBD - pip install gevent-socketio - -or from source:: - - git clone git://github.com/abourget/gevent-socketio.git - cd gevent-socketio - python setup.py install - -For development, run instead of ``install``:: - - python setup.py develop - -If you want to do all of that in a virtualenv, run:: - - virtualenv env - . env/bin/activate - python setup.py develop # or install +TODO +============ +* Framework support diff --git a/bootstrap.py b/bootstrap.py deleted file mode 100644 index 1b28969..0000000 --- a/bootstrap.py +++ /dev/null @@ -1,170 +0,0 @@ -############################################################################## -# -# Copyright (c) 2006 Zope Foundation and Contributors. -# All Rights Reserved. -# -# This software is subject to the provisions of the Zope Public License, -# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED -# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS -# FOR A PARTICULAR PURPOSE. -# -############################################################################## -"""Bootstrap a buildout-based project - -Simply run this script in a directory containing a buildout.cfg. -The script accepts buildout command-line options, so you can -use the -c option to specify an alternate configuration file. -""" - -import os -import shutil -import sys -import tempfile - -from optparse import OptionParser - -tmpeggs = tempfile.mkdtemp() - -usage = '''\ -[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] - -Bootstraps a buildout-based project. - -Simply run this script in a directory containing a buildout.cfg, using the -Python that you want bin/buildout to use. - -Note that by using --find-links to point to local resources, you can keep -this script from going over the network. -''' - -parser = OptionParser(usage=usage) -parser.add_option("-v", "--version", help="use a specific zc.buildout version") - -parser.add_option("-t", "--accept-buildout-test-releases", - dest='accept_buildout_test_releases', - action="store_true", default=False, - help=("Normally, if you do not specify a --version, the " - "bootstrap script and buildout gets the newest " - "*final* versions of zc.buildout and its recipes and " - "extensions for you. If you use this flag, " - "bootstrap and buildout will get the newest releases " - "even if they are alphas or betas.")) -parser.add_option("-c", "--config-file", - help=("Specify the path to the buildout configuration " - "file to be used.")) -parser.add_option("-f", "--find-links", - help=("Specify a URL to search for buildout releases")) - - -options, args = parser.parse_args() - -###################################################################### -# load/install setuptools - -to_reload = False -try: - import pkg_resources - import setuptools -except ImportError: - ez = {} - - try: - from urllib.request import urlopen - except ImportError: - from urllib2 import urlopen - - # XXX use a more permanent ez_setup.py URL when available. - exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' - ).read(), ez) - setup_args = dict(to_dir=tmpeggs, download_delay=0) - ez['use_setuptools'](**setup_args) - - if to_reload: - reload(pkg_resources) - import pkg_resources - # This does not (always?) update the default working set. We will - # do it. - for path in sys.path: - if path not in pkg_resources.working_set.entries: - pkg_resources.working_set.add_entry(path) - -###################################################################### -# Install buildout - -ws = pkg_resources.working_set - -cmd = [sys.executable, '-c', - 'from setuptools.command.easy_install import main; main()', - '-mZqNxd', tmpeggs] - -find_links = os.environ.get( - 'bootstrap-testing-find-links', - options.find_links or - ('http://downloads.buildout.org/' - if options.accept_buildout_test_releases else None) - ) -if find_links: - cmd.extend(['-f', find_links]) - -setuptools_path = ws.find( - pkg_resources.Requirement.parse('setuptools')).location - -requirement = 'zc.buildout' -version = options.version -if version is None and not options.accept_buildout_test_releases: - # Figure out the most recent final version of zc.buildout. - import setuptools.package_index - _final_parts = '*final-', '*final' - - def _final_version(parsed_version): - for part in parsed_version: - if (part[:1] == '*') and (part not in _final_parts): - return False - return True - index = setuptools.package_index.PackageIndex( - search_path=[setuptools_path]) - if find_links: - index.add_find_links((find_links,)) - req = pkg_resources.Requirement.parse(requirement) - if index.obtain(req) is not None: - best = [] - bestv = None - for dist in index[req.project_name]: - distv = dist.parsed_version - if _final_version(distv): - if bestv is None or distv > bestv: - best = [dist] - bestv = distv - elif distv == bestv: - best.append(dist) - if best: - best.sort() - version = best[-1].version -if version: - requirement = '=='.join((requirement, version)) -cmd.append(requirement) - -import subprocess -if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: - raise Exception( - "Failed to execute command:\n%s", - repr(cmd)[1:-1]) - -###################################################################### -# Import and run buildout - -ws.add_entry(tmpeggs) -ws.require(requirement) -import zc.buildout.buildout - -if not [a for a in args if '=' not in a]: - args.append('bootstrap') - -# if -c was provided, we push it back into args for buildout' main function -if options.config_file is not None: - args[0:0] = ['-c', options.config_file] - -zc.buildout.buildout.main(args) -shutil.rmtree(tmpeggs) diff --git a/buildout.cfg b/buildout.cfg deleted file mode 100644 index fc82915..0000000 --- a/buildout.cfg +++ /dev/null @@ -1,28 +0,0 @@ -[buildout] -develop = . -parts = python - test -newest = false -eggs = gevent - gevent-websocket - gevent-socketio - greenlet - -extensions = mr.developer -auto-checkout = * -sources-dir = external - -[sources] -gevent = git https://github.com/surfly/gevent.git -gevent-websocket = hg https://bitbucket.org/Jeffrey/gevent-websocket - -[python] -recipe = zc.recipe.egg -interpreter = python -eggs = ${buildout:eggs} - -[test] -recipe = zc.recipe.testrunner -eggs = ${buildout:eggs} - pytest - mock diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index f89d0f4..0000000 --- a/debian/changelog +++ /dev/null @@ -1,5 +0,0 @@ -python-gevent-socketio (0.3.5~rc2) precise; urgency=low - - * New version - - -- Alexandre Bourget Tue, 10 Jul 2012 23:38:22 +0000 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index 7f8f011..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -7 diff --git a/debian/control b/debian/control deleted file mode 100644 index d69323d..0000000 --- a/debian/control +++ /dev/null @@ -1,18 +0,0 @@ -Source: python-gevent-socketio -Section: python -Priority: extra -Maintainer: Alexandre Bourget -Build-Depends: python-all, python-setuptools, python-gevent, python-greenlet, python-gevent-websocket, debhelper (>= 7) -Standards-Version: 3.9.3 -Homepage: http://gevent-socketio.readthedocs.org/en/latest/ - -Package: python-gevent-socketio -Architecture: all -Section: python -Priority: extra -Depends: ${python:Depends} -Homepage: http://gevent-socketio.readthedocs.org/en/latest/ -Description: Python implementation of the Socket.IO server library - Socket.IO is a WebSocket-like abstraction that enables real-time communication - between a browser and a server. gevent-socketio is a Python implementation of - the protocol. diff --git a/debian/copyright b/debian/copyright deleted file mode 100644 index d6a6d50..0000000 --- a/debian/copyright +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2012, Noppo (Jeffrey Gelens) -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. -Neither the name of the Noppo nor the names of its contributors may be -used to endorse or promote products derived from this software without specific -prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/debian/docs b/debian/docs deleted file mode 100644 index 24948f1..0000000 --- a/debian/docs +++ /dev/null @@ -1,2 +0,0 @@ -AUTHORS -README.rst diff --git a/debian/rules b/debian/rules deleted file mode 100755 index bef222c..0000000 --- a/debian/rules +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/make -f - -%: - dh $@ --buildsystem=python_distutils --with=python2 diff --git a/debian/source/format b/debian/source/format deleted file mode 100644 index 89ae9db..0000000 --- a/debian/source/format +++ /dev/null @@ -1 +0,0 @@ -3.0 (native) diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 799d54b..0000000 --- a/docs/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/gevent-socketio.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/gevent-socketio.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/gevent-socketio" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/gevent-socketio" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 092fab1..0000000 --- a/docs/make.bat +++ /dev/null @@ -1,190 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source -set I18NSPHINXOPTS=%SPHINXOPTS% source -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\gevent-socketio.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\gevent-socketio.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -:end diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 5301eb0..0000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# -# gevent-socketio documentation build configuration file, created by -# sphinx-quickstart on Tue Mar 13 20:43:40 2012. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os -import datetime -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -here = os.path.dirname(__file__) -socketio_path = os.path.abspath(os.path.join(here, '../..')) -sys.path.insert(0, socketio_path) -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'gevent-socketio' -copyright = '2011-%s, Jeffrey Gelens, Alexandre Bourget, and John Anderson' % datetime.datetime.now().year - - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '0.3.1' -# The full version, including alpha/beta/rc tags. -release = '0.3.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'gevent-socketiodoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'gevent-socketio.tex', u'gevent-socketio Documentation', - u'Jeffrey Gelens,Alex Bourget,John Anderson', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'gevent-socketio', u'gevent-socketio Documentation', - [u'Jeffrey Gelens,Alex Bourget,John Anderson'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'gevent-socketio', u'gevent-socketio Documentation', - u'Jeffrey Gelens,Alex Bourget,John Anderson', 'gevent-socketio', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/docs/source/handler.rst b/docs/source/handler.rst deleted file mode 100644 index 35cdfb1..0000000 --- a/docs/source/handler.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. _handler_module: - -:mod:`socketio.handler` -======================= - -This is a lower-level transports handler. It is responsible for calling your WSGI application. - -.. automodule:: socketio.handler - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index b4979a3..0000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,373 +0,0 @@ -.. gevent-socketio documentation master file, created by - sphinx-quickstart on Tue Mar 13 20:43:40 2012. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Gevent-socketio documentation -============================= - -.. toctree:: - :maxdepth: 2 - -Introduction ------------- - -Socket.IO is a WebSocket-like abstraction that enables real-time -communication between a browser and a server. ``gevent-socketio`` is a -Python implementation of the protocol. - -The reference server implementation of Socket.IO runs on Node.js and was -developed by LearnBoost. There are now server implementations in a -variety of languages. - -One aim of this project is to provide a single ``gevent``-based -API that works across the different WSGI-based web frameworks out -there (Pyramid, Pylons, Flask, web2py, Django, etc...). Only ~3 lines -of code are required to tie-in ``gevent-socketio`` in your framework. -Note: you need to use the ``gevent`` python WSGI server to use -``gevent-socketio``. - -**Namespaces**: since you mostly have **one** websocket/socket.io -endpoint per website, it is important to be able to namespace the -different real-time activities of the different pages or parts of -your site, just like you need routes to map URLs to different parts -of your code. The Socket.IO 0.7+ namespaces are a welcome addition, -and if you don't use Socket.IO, you'll probably end-up writing your -own namespacing mechanism at some point. - -**Named events**: To distinguish the messages that are coming and -going, you most probably want to give them some name. Here again, not -using Socket.IO, you will find yourself implementing a way to tag your -packets with names representing different tasks or actions to -perform. With Socket.IO 0.6 or with normal WebSockets, you would -probably encode a JSON object with one of the keys that is reserved -for that (I used ``{"type": "submit_something"}``. Socket.IO 0.7+ -implements named events, which put that information in a terse form on -the wire. It also allows you to define callbacks, that can be -acknowledged by the other endpoint, and then fire back your function -with some return parameters. Something great for RPC, that you'd need -to implement yourself the moment you need it. - -**Transports**: One of the main feature of Socket.IO is the -abstraction of the transport, that gives you real-time web support -down to Internet Explorer 6.0, using long-polling methods. It will -also use native WebSockets when available to the browser, for even -lower latencies. Currently supported transports: ``websocket``, -``flashsocket``, ``htmlfile``, ``xhr-multipart``, ``xhr-polling``, -``jsonp-polling``. - -This implementation covers nearly all the features of the Socket.IO -0.7+ (up to at least 0.9.1) protocol, with events, callbacks. It adds -security in a pythonic way with granular ACLs (which don't exist in -the Node.js version) at the method level. The project has several -examples in the source code and in the documentation. Any addition -and fixes to the docs are warmly welcomed. - - -Concepts --------- - -In order to understand the following documentation articles, let's -clarify some of the terms used: - -A **Namespace** is like a controller in the MVC world. It encompasses -a set of methods that are logically in it. For example, the -``send_private_message`` event would be in the ``/chat`` namespace, as -well as the ``kick_ban`` event. Whereas the ``scan_files`` event -would be in the ``/filesystem`` namespace. Each namespace is -represented by a sub-class of :class:`BaseNamespace`. A simple -example would be, on the client side (the browser): - -.. code-block:: javascript - - var socket = io.connect("/chat"); - -having loaded the ``socket.io.js`` library somewhere in your . -On the server (this is a Pyramid example, but its pretty much the same -for other frameworks): - -.. code-block:: python - - from socketio.namespace import BaseNamespace - - class ChatNamespace(BaseNamespace): - def on_chat(self, msg): - self.emit('chat', msg) - - def socketio_service(request): - socketio_manage(request.environ, {'/chat': ChatNamespace}, - request) - return "out" - -Here we use :func:`socketio.socketio_manage` to start the Socket.IO -machine, and handle the real-time communication. - -You will come across the notion of a ``Socket``. This is a virtual -socket, that abstracts the fact that some transports are long-polling -and others are stateful (like a Websocket), and exposes the same -functionality for all. You can have many namespaces inside a Socket, -each delimited by their name like ``/chat``, ``/filesystem`` or -``/foobar``. Note also that there is a global namespace, identified -by an empty string. Some times, the global namespace has special -features, for backwards compatibilty reasons (we only have a global -namespace in version 0.6 of the protocol). For example, disconnecting -the global namespace means disconnect the full socket. Disconnecting -a qualified namespace, on the other hand, only removes access to that -namespace. - -The ``Socket`` is responsible from taking the `packets`, which are, in -the realm of a ``Namespace`` or a ``Socket`` object, a dictionary that -looks like: - -.. code-block:: python - - {"type": "event", - "name": "launch_superhero", - "args": ["Superman", 123, "km", {"hair_color": "brown"}]} - -These packets are serialized in a compact form when its time to put -them on the wire. Socket.IO also has some optimizations if we need to -send many packets on some long-polling transports. - - -At this point, if you don't know ``gevent``, you probably will want to -learn a bit more about it, since it is the base you will be working -on: - - http://www.gevent.org/ - - - -Getting started ---------------- - -Until we have a fully-fledged tutorial, please check out our example -applications and the API documentation. - -You can see a video that shows ``gevent-socketio`` in a live coding -presentation here: - - http://pyvideo.org/video/1573/gevent-socketio-cross-framework-real-time-web-li - -To learn how to build your Namespace (the object dealing with requests and replies), see: - - :ref:`namespace_module` - -See this doc for different servers integration: - - :ref:`server_integration` - -Examples --------- - -The ``gevent-socketio`` repository holds several examples: - - https://github.com/abourget/gevent-socketio/tree/master/examples - - * ``simple_chat`` is a bare-bone WSGI app with a minimal socketio integration - * ``simple_pyramid_chat`` is a simple chat application built on Pyramid - * ``live_cpu_graph`` is a simple realtime CPU graph (linux only) - * ``twitter_stream`` is a streaming feed of twitter updates - * ``pyramid_backbone_redis_chat`` is a Pyramid app using backbone.js and redis for pubsub - * ``pyramid_backbone_redis_chat_persistence`` is a Pyramid app using backbone.js, redis for pubsub and features persistence - * ``testapp`` is the app we use to test the different features, so there are a couple of more advanced use-cases demonstrated there - -``pyvore`` is an application that was developed to serve as real-time -chat in conferences like the PyCon: - - https://github.com/sontek/pyvore - -This app is a Django tic-tac-toe application that uses the latest -``gevent-socketio``: - - https://github.com/sontek/django-tictactoe - - -Security --------- - -``gevent-socketio`` provides method-level security, using an ACL -model. You can read more about it in the :ref:`namespace_module`, but -a basic example to secure one namespace would look like: - -.. code-block:: python - - class AdminInterface(BaseNamespace): - def get_initial_acl(self): - """Everything is locked at first""" - return [] - - def initialize(self): - # This here assumes you have passed in a `request` - # to your socketio_manage() call, it has that - # `is_admin` attribute - if not request.is_admin: - return - else: - self.lift_acl_restrictions() - - def on_blahblahblah(self, data): - """This can't be access until `lift_acl_restrictions()` has - been called - - """ - pass - - - -API docs --------- - -API documentation is where most of the juice/meat is. Read through -and you'll (hopefully) understand everything you need about -``gevent-socketio``. - -The manager is the function you call from your framework. It is in: - - :mod:`socketio` - -**Namespaces** are the main interface the developer is going to use. -You mostly define your own BaseNamespace derivatives, and -gevent-socketio maps the incoming messages to your methods -automatically: - - :mod:`socketio.namespace` - -**Mixins** are components you can add to your namespaces, to provided -added functionality. - - :mod:`socketio.mixins` - -**Sockets** are the virtual tunnels that are established and -abstracted by the different Transports. They basically expose -socket-like send/receive functionality to the Namespace objects. Even -when we use long-polling transports, only one Socket is created per -browser. - - :mod:`socketio.virtsocket` - -**Packet** is a library that handle the decoding of the messages -encoded in the Socket.IO dialect. They take dictionaries for -encoding, and return decoded dictionaries also. - - :mod:`socketio.packet` - -**Handler** is a lower-level transports handler. It is responsible -for calling your WSGI application - - :mod:`socketio.handler` - -**Transports** are responsible for translating the different fallback -mechanisms to one abstracted Socket, dealing with payload encoding, -multi-message multiplexing and their reverse operation. - - :mod:`socketio.transports` - -**Server** is the component used to hook Gevent and its WSGI server to -the WSGI app to be served, while dispatching any Socket.IO related -activities to the `handler` and the `transports`. - - :mod:`socketio.server` - -Auto-generated indexes: - -* :ref:`genindex` -* :ref:`modindex` - - -References ----------- - -LearnBoost's node.js version is the reference implementation, you can -find the server component at this address: - - https://github.com/learnboost/socket.io - -The client JavaScript library's development branch is here: - - https://github.com/LearnBoost/socket.io-client - -The specifications to the protocol are somehow in this repository: - - https://github.com/LearnBoost/socket.io-spec - -This is the original wow-website: - - http://socket.io - -Here is a list of the different frameworks integration to date, -although not all have upgraded to the latest version of -gevent-socketio: - - * pyramid_socketio: https://github.com/abourget/pyramid_socketio - * django-socketio: https://github.com/stephenmcd/django-socketio - -The Flask guys will be working on an integration layer soon. - - -Contacts --------- - -For any questions, you can use the Issue tracking at Github: - - https://github.com/abourget/gevent-socketio - https://github.com/abourget/gevent-socketio/issues - -The mailing list: - - https://groups.google.com/forum/#!forum/gevent-socketio - -The maintainers: - - https://twitter.com/bourgetalexndre - https://twitter.com/sontek - - -Credits -------- - -**Jeffrey Gellens** for starting and polishing this project over the years. - -PyCon 2012 and the Sprints, for bringing this project up to version -0.9 of the protocol. - -Current maintainers: - - * Alexandre Bourget - * John Anderson - -Contributors: - - * Denis Bilenko - * Bobby Powers - * Lon Ingram - * Eugene Baumstein - * Sébastien Béal - * jpellerin (JP) - * Philip Neustrom - * Jonas Obrist - * fabiodive - * Dan O'Neill - * Whit Morriss - * Chakib (spike) Benziane - * Vivek Venugopalan - * Vladimir Protasov - * Bruno Bigras - * Gabriel de Labacheliere - * Flavio Curella - * thapar - * Marconi Moreto - * sv1jsb - * Cliff Xuan - * Matt Billenstein - * Rolo - * Anthony Oliver - * Pierre Giraud - * m0sth8 - * Daniel Swarbrick - - -TODO ----- - -How to integrate your framework's "session" object (Beaker, memcached, or file-based). Beware: this can be tricky. You need to manage that yourself. diff --git a/docs/source/main.rst b/docs/source/main.rst deleted file mode 100644 index 7b23953..0000000 --- a/docs/source/main.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. _main_module: - -:mod:`socketio` -=============== - -This module holds the main hooking function for your framework of choice. - -Call the `socketio_manage` function from a view in your framework and this -will be the beginning of your Socket.IO journey. - -.. automodule:: socketio - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/mixins.rst b/docs/source/mixins.rst deleted file mode 100644 index 7097247..0000000 --- a/docs/source/mixins.rst +++ /dev/null @@ -1,12 +0,0 @@ -.. _mixins_module: - -:mod:`socketio.mixins` -====================== - -.. automodule:: socketio.mixins - -.. literalinclude:: ../../socketio/mixins.py - :pyobject: BroadcastMixin - -.. literalinclude:: ../../socketio/mixins.py - :pyobject: RoomsMixin diff --git a/docs/source/namespace.rst b/docs/source/namespace.rst deleted file mode 100644 index 856ec82..0000000 --- a/docs/source/namespace.rst +++ /dev/null @@ -1,236 +0,0 @@ -.. _namespace_module: - -:mod:`socketio.namespace` -========================= - -.. automodule:: socketio.namespace - -.. autoclass:: BaseNamespace - - -Namespace initialization ------------------------- - - You can override this method: - - .. automethod:: BaseNamespace.initialize - -Event flow ----------- - -This is an attempt at catching the gotchas of the Socket.IO protocol, -which, for historical reasons, sometimes have weird event flow. - -The first function to fire is ``initialize()``, which will be called -only if there is an incoming packet for the Namespace. A successful -javascript call to ``io.connect()`` **is not** sufficient for -``gevent-socketio`` to trigger the creation of a Namespace object. -Some event has to flow from the client to the server. The connection -will appear to have succeeded from the client's side, but that is -because ``gevent-socketio`` maintains the virtual socket up and running -before it hits your application. This is why it is a good pratice to -send a packet (often a ``login``, or ``subscribe`` or ``connect`` JSON -event, with ``io.emit()`` in the browser). - -If you're using the GLOBAL_NS, the ``recv_connect()`` will not fire on -your namespace, because when the connection is opened, there is no -such packet sent. The ``connect`` packet is only sent over (and -explicitly sent) by the javascript client when it tries to communicate -with some "non-global" namespaces. That is why it is recommended to -always use namespaces, to avoid having a different behavior for your -different namespaces. It also makes things explicit in your -application, when you have something such as ``/chat``, or -``/live_data``. Before a certain version of Socket.IO, there was only -a global namespace, and so this behavior was kept for backwards -compatibility. - -Then flows the normal events, back and forth as described elsewhere (elsewhere??). - -Upon disconnection, here is what happens: [INSERT HERE the details -flow of disconnection handling, events fired, physical closing of the -connection and ways to terminate a socket, when is the Namespace -killed, the state of the spawn'd processes for each Namespace and each -virtsocket. This really needs to be done, and I'd appreciate having -people investigate this thoroughly] - -There you go :) - - -Namespace instance properties ------------------------------ - - .. attribute:: BaseNamespace.session - - The :term:`session` is a simple ``dict`` that is created with - each :class:`~socketio.virtsocket.Socket` instance, and is - copied to each Namespace created under it. It is a general - purpose store for any data you want to associated with an open - :class:`~socketio.virtsocket.Socket`. - - .. attribute:: BaseNamespace.request - - This is the ``request`` object (or really, any object) that you - have passed as the ``request`` parameter to the - :func:`~socketio.socketio_manage` function. - - .. attribute:: BaseNamespace.ns_name - - The name of the namespace, like ``/chat`` or the empty string, - for the "global" namespace. - - .. attribute:: BaseNamespace.environ - - The ``environ`` WSGI dictionary, as it was received upon - reception of the **first** request that established the virtual - Socket. This will never contain the subsequent ``environ`` for - the next polling, so beware when using cookie-based sessions - (like Beaker). - - .. attribute:: BaseNamespace.socket - - A reference to the :class:`~socketio.virtsocket.Socket` - instance this namespace is attached to. - -Sending data ------------- - - Functions to send data through the socket: - - .. automethod:: BaseNamespace.emit - - .. automethod:: BaseNamespace.send - - .. automethod:: BaseNamespace.error - - .. automethod:: BaseNamespace.disconnect - - -Dealing with incoming data --------------------------- - - .. automethod:: BaseNamespace.recv_connect - - .. automethod:: BaseNamespace.recv_message - - .. automethod:: BaseNamespace.recv_json - - .. automethod:: BaseNamespace.recv_error - - .. automethod:: BaseNamespace.recv_disconnect - - .. method:: BaseNamespace.exception_handler_decorator(fn) - - This method can be a static, class or bound method (that is, with - ``@staticmethod``, ``@classmethod`` or without). It receives one - single parameter, and that parameter will be the function the - framework is trying to call because some information arrived from - the remote client, for instance: ``on_*`` and ``recv_*`` - functions that you declared on your namespace. - - The decorator is also used to wrap called to - ``self.spawn(self.job_something)``, so that if anything happens - after you've spawn'd a greenlet, it will still catch it and - handle it. - - It should return a decorator with exception handling properly - dealt with. For example: - - .. code-block:: python - - import traceback, sys - import logging - def exception_handler_decorator(self, fn): - def wrap(*args, **kwargs): - try: - return fn(*args, **kwargs) - except Exception, e: - stack = traceback.format_exception(*sys.exc_info()) - db.Evtrack.write("socketio_exception", - {"error": str(e), - "trace": stack}, - self.request.email) - logging.getLogger('exc_logger').exception(e) - return wrap - - - .. automethod:: BaseNamespace.process_event - - You would override this method only if you are not completely - satisfied with the automatic dispatching to ``on_``-prefixed - methods. You could then implement your own dispatch. See the - source code for inspiration. - - -Process management ------------------- - - Managing the different callbacks, greenlets and tasks you spawn from - this namespace: - - .. automethod:: BaseNamespace.spawn - - .. automethod:: BaseNamespace.kill_local_jobs - -ACL system ----------- - - The ACL system grants access to the different ``on_*()`` and - ``recv_*()`` methods of your subclass. - - Developers will normally override :meth:`get_initial_acl` to - return a list of the functions they want to initially open. - Usually, it will be an ``on_connect`` event handler, that will - perform authentication and/or authorization, set some variables - on the Namespace, and then open up the rest of the Namespace - using :meth:`lift_acl_restrictions` or more granularly with - :meth:`add_acl_method` and :meth:`del_acl_method`. It is also - possible to check these things inside :meth:`initialize` when, - for example, you have authenticated a Global Namespace object, - and you want to re-use those credentials or authentication infos - in a new Namespace: - - .. code-block:: python - - # GLOBAL_NS = '' - - class MyNamespace(BaseNamespace): - ... - def initialize(self): - self.my_auth = MyAuthObjet() - if self.socket[GLOBAL_NS].my_auth.logged_in == True: - self.my_auth.logged_in = True - - The content of the ACL is a list of strings corresponding to the full name - of the methods defined on your subclass, like: ``"on_my_event"`` or - ``"recv_json"``. - - .. automethod:: BaseNamespace.get_initial_acl - - .. automethod:: BaseNamespace.add_acl_method - - .. automethod:: BaseNamespace.del_acl_method - - .. automethod:: BaseNamespace.lift_acl_restrictions - - .. automethod:: BaseNamespace.reset_acl - - This function is used internally, but can be useful to the developer: - - .. automethod:: is_method_allowed - - This is the attribute where the allowed methods are stored, as a list of - strings, or a single ``None``:: - - .. autoattribute:: allowed_methods - -Low-level methods ------------------ - - Packet dispatching methods. These functions are normally not overriden if - you are satisfied with the normal dispatch behavior: - - .. automethod:: BaseNamespace.process_packet - - .. automethod:: BaseNamespace.call_method_with_acl - - .. automethod:: BaseNamespace.call_method diff --git a/docs/source/packet.rst b/docs/source/packet.rst deleted file mode 100644 index bc459c4..0000000 --- a/docs/source/packet.rst +++ /dev/null @@ -1,185 +0,0 @@ -.. _packet_module: - -:mod:`socketio.packet` -====================== - -The day to day user doesn't need to use this module directly. - -The packets used internally (that might be exposed if you override the -:meth:`~socketio.namespace.BaseNamespace.process_packet` method of -your Namespace) are dictionaries, and are different from one message -type to another. - -Internal packet types ---------------------- - -Here is a list of message types available in the -Socket.IO protocol: - -The connect packet -~~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - {"type": "connect", - "qs": "", - "endpoint": "/chat"} - -The ``qs`` parameter is a query string you can add to the io.connect('/chat?a=b'); calls on the client side. - -The **message** packet, equivalent to Socket.IO version 0.6's string message: - -.. code-block:: python - - {"type": "message", - "data": "this is the sent string", - "endpoint": "/chat"} - - {"type": "message", - "data": "some message, but please reply", - "ack": True, - "id": 5, - "endpoint": "/chat"} - -This last message includes a **msg_id**, and asks for an ack, which you can -reply to with ``self.ack()``, so that the client-side callback is fired upon -reception. - -The json packet -~~~~~~~~~~~~~~~ - -The **json** packet is like a message, with no name (unlike events) but with -structure JSON data attached. It is automatically decoded by gevent-socketio. - -.. code-block:: python - - {"type": "json", - "data": {"this": "is a json object"}, - "endpoint": "/chat"} - - {"type": "json", - "data": {"this": "is a json object", "please": "reply"}, - "ack": True, - "id": 5, - "endpoint": "/chat"} - -The same ``ack`` mechanics also apply for the ``json`` packet. - -The event packet -~~~~~~~~~~~~~~~~ - -The **event** packet holds a ``name`` and some ``args`` as a list. They are -taken as a list on the browser side (you can ``socket.emit("event", many, -parameters``) in the browser) and passed in as is. - -.. code-block:: python - - {"type": "event", - "endpoint": "/chat", - "name": "my_event", - "args": []} - - {"type": "event", - "endpoint": "/chat", - "name": "my_event", - "ack": True, - "id": 123, - "args": [{"my": "object"}, 2, "mystring"]} - -The same ack semantics apply here as well. - -[INSERT: mark the difference between when YOU create the packet, and when -you receive it, and what you must do with it according to different ack values] - -The heartbeat packet -~~~~~~~~~~~~~~~~~~~~ - -The **heartbeat** packet just marks the connection as alive for another amount -of time. - -.. code-block:: python - - {"type": "heartbeat", - "endpoint": ""} - -This packet is for the global namespace (or empty namespace). - -Ack mechanics -------------- - -The client sends a message of the sort: - -.. code-block:: python - - {"type": "message", - "id": 140, - "ack": True, - "endpoint": "/tobi", - "data": ''} - -The 'ack' value is 'true', marking that we want an automatic 'ack' when it -receives the packet. The Node.js version sends the ack itself, without any -server-side code interaction. It dispatches the packet only after sending back -an ack, so the ack isn't really a reply. It's just marking the server received -it, but not if the event/message/json was properly processed. - -The automated reply from such a request is: - -.. code-block:: python - - {"type": "ack", - "ackId": 140, - "endpoint": '', - "args": []} - -Where 'ackId' corresponds to the 'id' of the originating message. Upon -reception of this 'ack' message, the client then looks in an object if there -is a callback function to call associated with this message id (140). If so, -runs it, otherwise, drops the packet. - -There is a second way to ask for an ack, sending a packet like this: - -.. code-block:: python - - {"type": "event", - "id": 1, - "ack": "data", - "endpoint": '', - "name": 'tobi', - "args": []} - - {"type": "json", - "id": 1, - "ack": "data", - "endpoint": '', - "data": {"a": "b"}} - -and the same goes for a 'message' packet, which has the 'ack' equal to 'data'. -When the server receives such a packet, it dispatches the corresponding event -(either the named event specified in an 'event' type packet, or 'message' or -'json, if the type is so), and *adds* as a parameter, in addition to the -'args' passed by the event (or 'data' for 'message'/'json'), the ack() function -to call (it encloses the packet 'id' already). Any number of arguments passed -to that 'ack()' function will be passed on to the client-side, and given as -parameter on the client-side function. - -That is the returning 'ack' message, with the data ready to be passed as -arguments to the saved callback on the client side: - -.. code-block:: python - - {"type": "ack", - "ackId": 12, - "endpoint": '', - "args": ['woot', 'wa']} - -To learn more, see the `test_packet.py `_ test cases. It also shows the serialization that happens on the wire. - - -Other module members --------------------- - -.. automodule:: socketio.packet - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/server.rst b/docs/source/server.rst deleted file mode 100644 index 47cbf5c..0000000 --- a/docs/source/server.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. _server_module: - -:mod:`socketio.server` -====================== - -This is the component used to hook Gevent and its WSGI server to -the WSGI app to be served, while dispatching any Socket.IO related -activities to the `handler` and the `transports`. - -.. automodule:: socketio.server - :members: - :undoc-members: - :show-inheritance: - :special-members: __init__ diff --git a/docs/source/server_integration.rst b/docs/source/server_integration.rst deleted file mode 100644 index 3158ba0..0000000 --- a/docs/source/server_integration.rst +++ /dev/null @@ -1,199 +0,0 @@ -.. _server_integration: - -Server integration layers -========================= - -As gevent-socketio runs on top of Gevent, you need a Gevent-based -server, to yield the control cooperatively to the Greenlets in there. - -gunicorn --------- -If you have a python file that includes a WSGI application, for gunicorn -integration all you have to do is include the :mod:`socketio.sgunicorn` - -.. code-block:: bash - - gunicorn --worker-class socketio.sgunicorn.GeventSocketIOWorker module:app - - -paster / Pyramid's pserve -------------------------- - - -Through Gunicorn -^^^^^^^^^^^^^^^^ - -Gunicorn will handle workers for you and has other features. - -For paster, you just have to define the configuration like this: - -.. code-block:: ini - - [server:main] - use = egg:gunicorn#main - host = 0.0.0.0 - port = 6543 - workers = 4 - worker_class = socketio.sgunicorn.GeventSocketIOWorker - -Directly through gevent -^^^^^^^^^^^^^^^^^^^^^^^ - -Straight gevent integration is the simplest and has no dependencies. - -In your .ini file: - -.. code-block:: ini - - [server:main] - use = egg:gevent-socketio#paster - host = 0.0.0.0 - port = 6543 - resource = socket.io - transports = websocket, xhr-polling, xhr-multipart - policy_server = True - policy_listener_host = 0.0.0.0 - policy_listener_port = 10843 - -``policy_listener_host`` defaults to ``host``, -``policy_listener_port`` defaults to ``10843``, ``transports`` -defaults to all transports, ``policy_server`` defaults to ``False`` in -here, ``resource`` defaults to ``socket.io``. - -So you can have a slimmed-down version: - -.. code-block:: ini - - [server:main] - use = egg:gevent-socketio#paster - host = 0.0.0.0 - port = 6543 - - - -django runserver ----------------- -You can either define a wsgi app and launch it with gunicorn: - -``wsgi.py``: - -.. code-block:: python - - import django.core.handlers.wsgi - import os - - os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' - app = django.core.handlers.wsgi.WSGIHandler() - -from commandline: - -.. code-block:: bash - - gunicorn --worker-class socketio.sgunicorn.GeventSocketIOWorker wsgi:app - - -or you can use gevent directly: - -``run.py`` - -.. code-block:: python - - #!/usr/bin/env python - from gevent import monkey - from socketio.server import SocketIOServer - import django.core.handlers.wsgi - import os - import sys - - monkey.patch_all() - - try: - import settings - except ImportError: - sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) - sys.exit(1) - - PORT = 9000 - - os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' - - application = django.core.handlers.wsgi.WSGIHandler() - - sys.path.insert(0, os.path.join(settings.PROJECT_ROOT, "apps")) - - if __name__ == '__main__': - print 'Listening on http://127.0.0.1:%s and on port 10843 (flash policy server)' % PORT - SocketIOServer(('', PORT), application, resource="socket.io").serve_forever() - - -Databases -========= - -Since gevent is a cooperative concurrency library, no process or -routine or library must block on I/O without yielding control to the -``gevent`` hub, if you want your application to be fast and efficient. -Making these libraries compatible with such a concurrency model is -often called `greening`, in reference to `Green threads -`_. - - - -You will need `green`_ databases APIs to gevent to work correctly. See: - - * MySQL: - * PyMySQL https://github.com/petehunt/PyMySQL/ - * PostgreSQL: - * psycopg2 http://initd.org/psycopg/docs/advanced.html#index-8 - * psycogreen https://bitbucket.org/dvarrazzo/psycogreen/src - - - -Web server front-ends -===================== - -If your web server does not support websockets, you will not be able -to use this transport, although the other transports may -work. However, this would diminish the value of using real-time -communications. - -The websocket implementation in the different web servers is getting -better every day, but before investing too much too quickly, you might -want to have a look at your web server's status on the subject. - -[INSERT THE STATE OF THE DIFFERENT SERVER IMPLEMENTATIONS SUPPORTING WEBSOCKET -FORWARDING] - -nginx status ----------------- - -Nginx added the ability to support websockets with version 1.3.13 but it requires a bit of explicit configuration. - -See: http://nginx.org/en/docs/http/websocket.html - -Assuming your config is setup to proxy to your gevent server via something like this: - -.. code-block:: nginx - - location / { - proxy_pass http://127.0.0.1:7000; - proxy_redirect off; - } - -You'll just need to add this additional location section. Note in this example we're using ``/socket.io`` as the entry point (you might have to change it) - -.. code-block:: nginx - - location /socket.io { - proxy_pass http://127.0.0.1:7000/socket.io; - proxy_redirect off; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - } - -Make sure you're running the latest version of Nginx (or atleast >= 1.3.13). Older versions don't support websockets, and the client will have to fallback to long polling. - -Apache - -Using HAProxy to load-balance - diff --git a/docs/source/sgunicorn.rst b/docs/source/sgunicorn.rst deleted file mode 100644 index 7d43319..0000000 --- a/docs/source/sgunicorn.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _gunicorn_module: - -:mod:`socketio.sgunicorn` -========================= - -.. automodule:: socketio.sgunicorn - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/transports.rst b/docs/source/transports.rst deleted file mode 100644 index 97e22e2..0000000 --- a/docs/source/transports.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. _transports_module: - -:mod:`socketio.transports` -========================== - -This is largely an internal module, responsible for translating the -different fallback mechanisms to one abstracted Socket, dealing with -payload encoding, multi-message multiplexing and their reverse operation. - -.. automodule:: socketio.transports - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/virtsocket.rst b/docs/source/virtsocket.rst deleted file mode 100644 index 889bb7f..0000000 --- a/docs/source/virtsocket.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. _virtsocket_module: - -:mod:`socketio.virtsocket` -========================== - -.. automodule:: socketio.virtsocket - :members: - :undoc-members: - :show-inheritance: - - diff --git a/examples/cross_origin/README.rst b/examples/cross_origin/README.rst deleted file mode 100644 index faef03b..0000000 --- a/examples/cross_origin/README.rst +++ /dev/null @@ -1,40 +0,0 @@ -================================== -gevent-socketio cross-site example -================================== - -This example app demonstrates that you can use socket.io (0.9) -connections from hosts other than the origin host with -gevent-socketio. - -To run the example, first install set up your gevent-socketio -development environment, then install the example's requirements -into the same virtualenv by running:: - - pip install -r requirements.txt - -in this directory. Then in two separate shells, start ``web.py`` and -``sock.py``:: - - python web.py - -Then in shell two:: - - python sock.py - -The two servers run on different ports, simulating a common case where -the main web application is running on one host and the socket.io -server is running on a separate host. - -When both are running, navigate to http://localhost:8080/ and -follow the directions that appear there to see cross-site socket.io -in action. - -socket.io.js 0.8 vs 0.9 ------------------------ - -Note that socket.io.js 0.8 works with gevent-socketio for cross-origin requests -without any special headers in the handshake phase. But socket.io.js -0.9 makes a change to how it sends the XHR handshake request: it sets -``withCredentials = true``, which requires that the socket.io server -return an ``Access-Control-Allow-Origin`` header that mentions the -origin server. diff --git a/examples/cross_origin/requirements.txt b/examples/cross_origin/requirements.txt deleted file mode 100644 index d224d81..0000000 --- a/examples/cross_origin/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -bottle>=0.10.6 diff --git a/examples/cross_origin/sock.py b/examples/cross_origin/sock.py deleted file mode 100644 index a72d0ad..0000000 --- a/examples/cross_origin/sock.py +++ /dev/null @@ -1,23 +0,0 @@ -from gevent import monkey; monkey.patch_all() - -from bottle import Bottle, request -from socketio import server, namespace, socketio_manage - -app = Bottle() - -class Hello(namespace.BaseNamespace): - - def on_hello(self, data): - print "hello", data - self.emit('greetings', {'from': 'sockets'}) - - -@app.route('/socket.io/') -def socketio(*arg, **kw): - socketio_manage(request.environ, {'': Hello}, request=request) - return "out" - - -if __name__ == '__main__': - server.SocketIOServer( - ('localhost', 9090), app, policy_server=False).serve_forever() diff --git a/examples/cross_origin/static/0.8/socket.io.js b/examples/cross_origin/static/0.8/socket.io.js deleted file mode 100644 index b3f19c0..0000000 --- a/examples/cross_origin/static/0.8/socket.io.js +++ /dev/null @@ -1,3704 +0,0 @@ -/*! Socket.IO.js build:0.8.2, development. Copyright(c) 2011 LearnBoost MIT Licensed */ - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports) { - - /** - * IO namespace. - * - * @namespace - */ - - var io = exports; - - /** - * Socket.IO version - * - * @api public - */ - - io.version = '0.8.2'; - - /** - * Protocol implemented. - * - * @api public - */ - - io.protocol = 1; - - /** - * Available transports, these will be populated with the available transports - * - * @api public - */ - - io.transports = []; - - /** - * Keep track of jsonp callbacks. - * - * @api private - */ - - io.j = []; - - /** - * Keep track of our io.Sockets - * - * @api private - */ - io.sockets = {}; - - - /** - * Manages connections to hosts. - * - * @param {String} uri - * @Param {Boolean} force creation of new socket (defaults to false) - * @api public - */ - - io.connect = function (host, details) { - var uri = io.util.parseUri(host) - , uuri - , socket; - - if ('undefined' != typeof document) { - uri.protocol = uri.protocol || document.location.protocol.slice(0, -1); - uri.host = uri.host || document.domain; - uri.port = uri.port || document.location.port; - } - - uuri = io.util.uniqueUri(uri); - - var options = { - host: uri.host - , secure: 'https' == uri.protocol - , port: uri.port || ('https' == uri.protocol ? 443 : 80) - , query: uri.query || '' - }; - - io.util.merge(options, details); - - if (options['force new connection'] || !io.sockets[uuri]) { - socket = new io.Socket(options); - } - - if (!options['force new connection'] && socket) { - io.sockets[uuri] = socket; - } - - socket = socket || io.sockets[uuri]; - - // if path is different from '' or / - return socket.of(uri.path.length > 1 ? uri.path : ''); - }; - -})('object' === typeof module ? module.exports : (window.io = {})); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, global) { - - /** - * Utilities namespace. - * - * @namespace - */ - - var util = exports.util = {}; - - /** - * Parses an URI - * - * @author Steven Levithan (MIT license) - * @api public - */ - - var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - - var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', - 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', - 'anchor']; - - util.parseUri = function (str) { - var m = re.exec(str || '') - , uri = {} - , i = 14; - - while (i--) { - uri[parts[i]] = m[i] || ''; - } - - return uri; - }; - - /** - * Produces a unique url that identifies a Socket.IO connection. - * - * @param {Object} uri - * @api public - */ - - util.uniqueUri = function (uri) { - var protocol = uri.protocol - , host = uri.host - , port = uri.port; - - if ('document' in global) { - host = host || document.domain; - port = port || (protocol == 'https' - && document.location.protocol !== 'https:' ? 443 : document.location.port); - } else { - host = host || 'localhost'; - - if (!port && protocol == 'https') { - port = 443; - } - } - - return (protocol || 'http') + '://' + host + ':' + (port || 80); - }; - - /** - * Mergest 2 query strings in to once unique query string - * - * @param {String} base - * @param {String} addition - * @api public - */ - - util.query = function (base, addition) { - var query = util.chunkQuery(base || '') - , components = []; - - util.merge(query, util.chunkQuery(addition || '')); - for (var part in query) { - if (query.hasOwnProperty(part)) { - components.push(part + '=' + query[part]); - } - } - - return components.length ? '?' + components.join('&') : ''; - }; - - /** - * Transforms a querystring in to an object - * - * @param {String} qs - * @api public - */ - - util.chunkQuery = function (qs) { - var query = {} - , params = qs.split('&') - , i = 0 - , l = params.length - , kv; - - for (; i < l; ++i) { - kv = params[i].split('='); - if (kv[0]) { - query[kv[0]] = decodeURIComponent(kv[1]); - } - } - - return query; - }; - - /** - * Executes the given function when the page is loaded. - * - * io.util.load(function () { console.log('page loaded'); }); - * - * @param {Function} fn - * @api public - */ - - var pageLoaded = false; - - util.load = function (fn) { - if ('document' in global && document.readyState === 'complete' || pageLoaded) { - return fn(); - } - - util.on(global, 'load', fn, false); - }; - - /** - * Adds an event. - * - * @api private - */ - - util.on = function (element, event, fn, capture) { - if (element.attachEvent) { - element.attachEvent('on' + event, fn); - } else if (element.addEventListener) { - element.addEventListener(event, fn, capture); - } - }; - - /** - * Generates the correct `XMLHttpRequest` for regular and cross domain requests. - * - * @param {Boolean} [xdomain] Create a request that can be used cross domain. - * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest. - * @api private - */ - - util.request = function (xdomain) { - - if ('undefined' != typeof window) { - if (xdomain && window.XDomainRequest) { - return new XDomainRequest(); - } - - if (window.XMLHttpRequest && (!xdomain || util.ua.hasCORS)) { - return new XMLHttpRequest(); - } - - if (!xdomain) { - try { - return new window.ActiveXObject('Microsoft.XMLHTTP'); - } catch(e) { } - } - } - - return null; - }; - - /** - * XHR based transport constructor. - * - * @constructor - * @api public - */ - - /** - * Change the internal pageLoaded value. - */ - - if ('undefined' != typeof window) { - util.load(function () { - pageLoaded = true; - }); - } - - /** - * Defers a function to ensure a spinner is not displayed by the browser - * - * @param {Function} fn - * @api public - */ - - util.defer = function (fn) { - if (!util.ua.webkit) { - return fn(); - } - - util.load(function () { - setTimeout(fn, 100); - }); - }; - - /** - * Merges two objects. - * - * @api public - */ - - util.merge = function merge (target, additional, deep, lastseen) { - var seen = lastseen || [] - , depth = typeof deep == 'undefined' ? 2 : deep - , prop; - - for (prop in additional) { - if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) { - if (typeof target[prop] !== 'object' || !depth) { - target[prop] = additional[prop]; - seen.push(additional[prop]); - } else { - util.merge(target[prop], additional[prop], depth - 1, seen); - } - } - } - - return target; - }; - - /** - * Merges prototypes from objects - * - * @api public - */ - - util.mixin = function (ctor, ctor2) { - util.merge(ctor.prototype, ctor2.prototype); - }; - - /** - * Shortcut for prototypical and static inheritance. - * - * @api private - */ - - util.inherit = function (ctor, ctor2) { - function f() {}; - f.prototype = ctor2.prototype; - ctor.prototype = new f; - }; - - /** - * Checks if the given object is an Array. - * - * io.util.isArray([]); // true - * io.util.isArray({}); // false - * - * @param Object obj - * @api public - */ - - util.isArray = Array.isArray || function (obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; - }; - - /** - * Intersects values of two arrays into a third - * - * @api public - */ - - util.intersect = function (arr, arr2) { - var ret = [] - , longest = arr.length > arr2.length ? arr : arr2 - , shortest = arr.length > arr2.length ? arr2 : arr; - - for (var i = 0, l = shortest.length; i < l; i++) { - if (~util.indexOf(longest, shortest[i])) - ret.push(shortest[i]); - } - - return ret; - } - - /** - * Array indexOf compatibility. - * - * @see bit.ly/a5Dxa2 - * @api public - */ - - util.indexOf = function (arr, o, i) { - if (Array.prototype.indexOf) { - return Array.prototype.indexOf.call(arr, o, i); - } - - for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0; - i < j && arr[i] !== o; i++); - - return j <= i ? -1 : i; - }; - - /** - * Converts enumerables to array. - * - * @api public - */ - - util.toArray = function (enu) { - var arr = []; - - for (var i = 0, l = enu.length; i < l; i++) - arr.push(enu[i]); - - return arr; - }; - - /** - * UA / engines detection namespace. - * - * @namespace - */ - - util.ua = {}; - - /** - * Whether the UA supports CORS for XHR. - * - * @api public - */ - - util.ua.hasCORS = 'undefined' != typeof window && window.XMLHttpRequest && - (function () { - try { - var a = new XMLHttpRequest(); - } catch (e) { - return false; - } - - return a.withCredentials != undefined; - })(); - - /** - * Detect webkit. - * - * @api public - */ - - util.ua.webkit = 'undefined' != typeof navigator - && /webkit/i.test(navigator.userAgent); - -})( - 'undefined' != typeof window ? io : module.exports - , this -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.EventEmitter = EventEmitter; - - /** - * Event emitter constructor. - * - * @api public. - */ - - function EventEmitter () {}; - - /** - * Adds a listener - * - * @api public - */ - - EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (io.util.isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; - }; - - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - - /** - * Adds a volatile listener. - * - * @api public - */ - - EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; - }; - - /** - * Removes a listener. - * - * @api public - */ - - EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (io.util.isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; - }; - - /** - * Removes all listeners for an event. - * - * @api public - */ - - EventEmitter.prototype.removeAllListeners = function (name) { - // TODO: enable this when node 0.5 is stable - //if (name === undefined) { - //this.$events = {}; - //return this; - //} - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; - }; - - /** - * Gets all listeners for a certain event. - * - * @api publci - */ - - EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!io.util.isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; - }; - - /** - * Emits an event. - * - * @api public - */ - - EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = Array.prototype.slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (io.util.isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; - }; - -})( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -/** - * Based on JSON2 (http://www.JSON.org/js.html). - */ - -(function (exports, nativeJSON) { - "use strict"; - - // use native JSON if it's available - if (nativeJSON && nativeJSON.parse){ - return exports.JSON = { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify - } - } - - var JSON = exports.JSON = {}; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + - f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; - }; - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value instanceof Date) { - value = date(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - -// If the JSON object does not yet have a parse method, give it one. - - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - -})( - 'undefined' != typeof io ? io : module.exports - , typeof JSON !== 'undefined' ? JSON : undefined -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Parser namespace. - * - * @namespace - */ - - var parser = exports.parser = {}; - - /** - * Packet types. - */ - - var packets = parser.packets = [ - 'disconnect' - , 'connect' - , 'heartbeat' - , 'message' - , 'json' - , 'event' - , 'ack' - , 'error' - , 'noop' - ]; - - /** - * Errors reasons. - */ - - var reasons = parser.reasons = [ - 'transport not supported' - , 'client not handshaken' - , 'unauthorized' - ]; - - /** - * Errors advice. - */ - - var advice = parser.advice = [ - 'reconnect' - ]; - - /** - * Shortcuts. - */ - - var JSON = io.JSON - , indexOf = io.util.indexOf; - - /** - * Encodes a packet. - * - * @api private - */ - - parser.encodePacket = function (packet) { - var type = indexOf(packets, packet.type) - , id = packet.id || '' - , endpoint = packet.endpoint || '' - , ack = packet.ack - , data = null; - - switch (packet.type) { - case 'error': - var reason = packet.reason ? indexOf(reasons, packet.reason) : '' - , adv = packet.advice ? indexOf(advice, packet.advice) : ''; - - if (reason !== '' || adv !== '') - data = reason + (adv !== '' ? ('+' + adv) : ''); - - break; - - case 'message': - if (packet.data !== '') - data = packet.data; - break; - - case 'event': - var ev = { name: packet.name }; - - if (packet.args && packet.args.length) { - ev.args = packet.args; - } - - data = JSON.stringify(ev); - break; - - case 'json': - data = JSON.stringify(packet.data); - break; - - case 'connect': - if (packet.qs) - data = packet.qs; - break; - - case 'ack': - data = packet.ackId - + (packet.args && packet.args.length - ? '+' + JSON.stringify(packet.args) : ''); - break; - } - - // construct packet with required fragments - var encoded = [ - type - , id + (ack == 'data' ? '+' : '') - , endpoint - ]; - - // data fragment is optional - if (data !== null && data !== undefined) - encoded.push(data); - - return encoded.join(':'); - }; - - /** - * Encodes multiple messages (payload). - * - * @param {Array} messages - * @api private - */ - - parser.encodePayload = function (packets) { - var decoded = ''; - - if (packets.length == 1) - return packets[0]; - - for (var i = 0, l = packets.length; i < l; i++) { - var packet = packets[i]; - decoded += '\ufffd' + packet.length + '\ufffd' + packets[i]; - } - - return decoded; - }; - - /** - * Decodes a packet - * - * @api private - */ - - var regexp = /^([^:]+):([0-9]+)?(\+)?:([^:]+)?:?(.*)?$/; - - parser.decodePacket = function (data) { - var pieces = data.match(regexp); - - if (!pieces) return {}; - - var id = pieces[2] || '' - , data = pieces[5] || '' - , packet = { - type: packets[pieces[1]] - , endpoint: pieces[4] || '' - }; - - // whether we need to acknowledge the packet - if (id) { - packet.id = id; - if (pieces[3]) - packet.ack = 'data'; - else - packet.ack = true; - } - - // handle different packet types - switch (packet.type) { - case 'error': - var pieces = data.split('+'); - packet.reason = reasons[pieces[0]] || ''; - packet.advice = advice[pieces[1]] || ''; - break; - - case 'message': - packet.data = data || ''; - break; - - case 'event': - try { - var opts = JSON.parse(data); - packet.name = opts.name; - packet.args = opts.args; - } catch (e) { } - - packet.args = packet.args || []; - break; - - case 'json': - try { - packet.data = JSON.parse(data); - } catch (e) { } - break; - - case 'connect': - packet.qs = data || ''; - break; - - case 'ack': - var pieces = data.match(/^([0-9]+)(\+)?(.*)/); - if (pieces) { - packet.ackId = pieces[1]; - packet.args = []; - - if (pieces[3]) { - try { - packet.args = pieces[3] ? JSON.parse(pieces[3]) : []; - } catch (e) { } - } - } - break; - - case 'disconnect': - case 'heartbeat': - break; - }; - - return packet; - }; - - /** - * Decodes data payload. Detects multiple messages - * - * @return {Array} messages - * @api public - */ - - parser.decodePayload = function (data) { - // IE doesn't like data[i] for unicode chars, charAt works fine - if (data.charAt(0) == '\ufffd') { - var ret = []; - - for (var i = 1, length = ''; i < data.length; i++) { - if (data.charAt(i) == '\ufffd') { - ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length))); - i += Number(length) + 1; - length = ''; - } else { - length += data.charAt(i); - } - } - - return ret; - } else { - return [parser.decodePacket(data)]; - } - }; - -})( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.Transport = Transport; - - /** - * This is the transport template for all supported transport methods. - * - * @constructor - * @api public - */ - - function Transport (socket, sessid) { - this.socket = socket; - this.sessid = sessid; - }; - - /** - * Apply EventEmitter mixin. - */ - - io.util.mixin(Transport, io.EventEmitter); - - /** - * Handles the response from the server. When a new response is received - * it will automatically update the timeout, decode the message and - * forwards the response to the onMessage function for further processing. - * - * @param {String} data Response from the server. - * @api private - */ - - Transport.prototype.onData = function (data) { - this.clearCloseTimeout(); - this.setCloseTimeout(); - - if (data !== '') { - // todo: we should only do decodePayload for xhr transports - var msgs = io.parser.decodePayload(data); - - if (msgs && msgs.length) { - for (var i = 0, l = msgs.length; i < l; i++) { - this.onPacket(msgs[i]); - } - } - } - - return this; - }; - - /** - * Handles packets. - * - * @api private - */ - - Transport.prototype.onPacket = function (packet) { - if (packet.type == 'heartbeat') { - return this.onHeartbeat(); - } - - if (packet.type == 'connect' && packet.endpoint == '') { - this.onConnect(); - } - - this.socket.onPacket(packet); - - return this; - }; - - /** - * Sets close timeout - * - * @api private - */ - - Transport.prototype.setCloseTimeout = function () { - if (!this.closeTimeout) { - var self = this; - - this.closeTimeout = setTimeout(function () { - self.onDisconnect(); - }, this.socket.closeTimeout); - } - }; - - /** - * Called when transport disconnects. - * - * @api private - */ - - Transport.prototype.onDisconnect = function () { - if (this.close) this.close(); - this.clearTimeouts(); - this.socket.onDisconnect(); - return this; - }; - - /** - * Called when transport connects - * - * @api private - */ - - Transport.prototype.onConnect = function () { - this.socket.onConnect(); - return this; - } - - /** - * Clears close timeout - * - * @api private - */ - - Transport.prototype.clearCloseTimeout = function () { - if (this.closeTimeout) { - clearTimeout(this.closeTimeout); - this.closeTimeout = null; - } - }; - - /** - * Clear timeouts - * - * @api private - */ - - Transport.prototype.clearTimeouts = function () { - this.clearCloseTimeout(); - - if (this.reopenTimeout) { - clearTimeout(this.reopenTimeout); - } - }; - - /** - * Sends a packet - * - * @param {Object} packet object. - * @api private - */ - - Transport.prototype.packet = function (packet) { - this.send(io.parser.encodePacket(packet)); - }; - - /** - * Send the received heartbeat message back to server. So the server - * knows we are still connected. - * - * @param {String} heartbeat Heartbeat response from the server. - * @api private - */ - - Transport.prototype.onHeartbeat = function (heartbeat) { - this.packet({ type: 'heartbeat' }); - }; - - /** - * Called when the transport opens. - * - * @api private - */ - - Transport.prototype.onOpen = function () { - this.open = true; - this.clearCloseTimeout(); - this.socket.onOpen(); - }; - - /** - * Notifies the base when the connection with the Socket.IO server - * has been disconnected. - * - * @api private - */ - - Transport.prototype.onClose = function () { - var self = this; - - /* FIXME: reopen delay causing a infinit loop - this.reopenTimeout = setTimeout(function () { - self.open(); - }, this.socket.options['reopen delay']);*/ - - this.open = false; - this.setCloseTimeout(); - this.socket.onClose(); - }; - - /** - * Generates a connection url based on the Socket.IO URL Protocol. - * See for more details. - * - * @returns {String} Connection url - * @api private - */ - - Transport.prototype.prepareUrl = function () { - var options = this.socket.options; - - return this.scheme() + '://' - + options.host + ':' + options.port + '/' - + options.resource + '/' + io.protocol - + '/' + this.name + '/' + this.sessid; - }; - - /** - * Checks if the transport is ready to start a connection. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ - - Transport.prototype.ready = function (socket, fn) { - fn.call(this); - }; -})( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io, global) { - - /** - * Expose constructor. - */ - - exports.Socket = Socket; - - /** - * Create a new `Socket.IO client` which can establish a persistent - * connection with a Socket.IO enabled server. - * - * @api public - */ - - function Socket (options) { - this.options = { - port: 80 - , secure: false - , document: 'document' in global ? document : false - , resource: 'socket.io' - , transports: io.transports - , 'connect timeout': 10000 - , 'try multiple transports': true - , 'reconnect': true - , 'reconnection delay': 500 - , 'reconnection limit': Infinity - , 'reopen delay': 3000 - , 'max reconnection attempts': 10 - , 'sync disconnect on unload': true - , 'auto connect': true - }; - - io.util.merge(this.options, options); - - this.connected = false; - this.open = false; - this.connecting = false; - this.reconnecting = false; - this.namespaces = {}; - this.buffer = []; - this.doBuffer = false; - - if (this.options['sync disconnect on unload'] && - (!this.isXDomain() || io.util.ua.hasCORS)) { - var self = this; - - io.util.on(global, 'beforeunload', function () { - self.disconnectSync(); - }, false); - } - - if (this.options['auto connect']) { - this.connect(); - } -}; - - /** - * Apply EventEmitter mixin. - */ - - io.util.mixin(Socket, io.EventEmitter); - - /** - * Returns a namespace listener/emitter for this socket - * - * @api public - */ - - Socket.prototype.of = function (name) { - if (!this.namespaces[name]) { - this.namespaces[name] = new io.SocketNamespace(this, name); - - if (name !== '') { - this.namespaces[name].packet({ type: 'connect' }); - } - } - - return this.namespaces[name]; - }; - - /** - * Emits the given event to the Socket and all namespaces - * - * @api private - */ - - Socket.prototype.publish = function () { - this.emit.apply(this, arguments); - - var nsp; - - for (var i in this.namespaces) { - if (this.namespaces.hasOwnProperty(i)) { - nsp = this.of(i); - nsp.$emit.apply(nsp, arguments); - } - } - }; - - /** - * Performs the handshake - * - * @api private - */ - - function empty () { }; - - Socket.prototype.handshake = function (fn) { - var self = this - , options = this.options; - - function complete (data) { - if (data instanceof Error) { - self.onError(data.message); - } else { - fn.apply(null, data.split(':')); - } - }; - - var url = [ - 'http' + (options.secure ? 's' : '') + ':/' - , options.host + ':' + options.port - , this.options.resource - , io.protocol - , io.util.query(this.options.query, 't=' + +new Date) - ].join('/'); - - if (this.isXDomain()) { - var insertAt = document.getElementsByTagName('script')[0] - , script = document.createElement('SCRIPT'); - - script.src = url + '&jsonp=' + io.j.length; - insertAt.parentNode.insertBefore(script, insertAt); - - io.j.push(function (data) { - complete(data); - script.parentNode.removeChild(script); - }); - } else { - var xhr = io.util.request(); - - xhr.open('GET', url, true); - xhr.onreadystatechange = function () { - if (xhr.readyState == 4) { - xhr.onreadystatechange = empty; - - if (xhr.status == 200) { - complete(xhr.responseText); - } else { - !self.reconnecting && self.onError(xhr.responseText); - } - } - }; - xhr.send(null); - } - }; - - /** - * Find an available transport based on the options supplied in the constructor. - * - * @api private - */ - - Socket.prototype.getTransport = function (override) { - var transports = override || this.transports, match; - - for (var i = 0, transport; transport = transports[i]; i++) { - if (io.Transport[transport] - && io.Transport[transport].check(this) - && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) { - return new io.Transport[transport](this, this.sessionid); - } - } - - return null; - }; - - /** - * Connects to the server. - * - * @param {Function} [fn] Callback. - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.connect = function (fn) { - if (this.connecting) { - return this; - } - - var self = this; - - this.handshake(function (sid, heartbeat, close, transports) { - self.sessionid = sid; - self.closeTimeout = close * 1000; - self.heartbeatTimeout = heartbeat * 1000; - self.transports = io.util.intersect( - transports.split(',') - , self.options.transports - ); - - function connect (transports){ - if (self.transport) self.transport.clearTimeouts(); - - self.transport = self.getTransport(transports); - if (!self.transport) return self.publish('connect_failed'); - - // once the transport is ready - self.transport.ready(self, function () { - self.connecting = true; - self.publish('connecting', self.transport.name); - self.transport.open(); - - if (self.options['connect timeout']) { - self.connectTimeoutTimer = setTimeout(function () { - if (!self.connected) { - self.connecting = false; - - if (self.options['try multiple transports']) { - if (!self.remainingTransports) { - self.remainingTransports = self.transports.slice(0); - } - - var remaining = self.remainingTransports; - - while (remaining.length > 0 && remaining.splice(0,1)[0] != - self.transport.name) {} - - if (remaining.length){ - connect(remaining); - } else { - self.publish('connect_failed'); - } - } - } - }, self.options['connect timeout']); - } - }); - } - - connect(); - - self.once('connect', function (){ - clearTimeout(self.connectTimeoutTimer); - - fn && typeof fn == 'function' && fn(); - }); - }); - - return this; - }; - - /** - * Sends a message. - * - * @param {Object} data packet. - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.packet = function (data) { - if (this.connected && !this.doBuffer) { - this.transport.packet(data); - } else { - this.buffer.push(data); - } - - return this; - }; - - /** - * Sets buffer state - * - * @api private - */ - - Socket.prototype.setBuffer = function (v) { - this.doBuffer = v; - - if (!v && this.connected && this.buffer.length) { - this.transport.payload(this.buffer); - this.buffer = []; - } - }; - - /** - * Disconnect the established connect. - * - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.disconnect = function () { - if (this.connected) { - if (this.open) { - this.of('').packet({ type: 'disconnect' }); - } - - // handle disconnection immediately - this.onDisconnect('booted'); - } - - return this; - }; - - /** - * Disconnects the socket with a sync XHR. - * - * @api private - */ - - Socket.prototype.disconnectSync = function () { - // ensure disconnection - var xhr = io.util.request() - , uri = this.resource + '/' + io.protocol + '/' + this.sessionid; - - xhr.open('GET', uri, true); - - // handle disconnection immediately - this.onDisconnect('booted'); - }; - - /** - * Check if we need to use cross domain enabled transports. Cross domain would - * be a different port or different domain name. - * - * @returns {Boolean} - * @api private - */ - - Socket.prototype.isXDomain = function () { - - var locPort = window.location.port || 80; - return this.options.host !== document.domain || this.options.port != locPort; - }; - - /** - * Called upon handshake. - * - * @api private - */ - - Socket.prototype.onConnect = function () { - if (!this.connected) { - this.connected = true; - this.connecting = false; - if (!this.doBuffer) { - // make sure to flush the buffer - this.setBuffer(false); - } - this.emit('connect'); - } - }; - - /** - * Called when the transport opens - * - * @api private - */ - - Socket.prototype.onOpen = function () { - this.open = true; - }; - - /** - * Called when the transport closes. - * - * @api private - */ - - Socket.prototype.onClose = function () { - this.open = false; - }; - - /** - * Called when the transport first opens a connection - * - * @param text - */ - - Socket.prototype.onPacket = function (packet) { - this.of(packet.endpoint).onPacket(packet); - }; - - /** - * Handles an error. - * - * @api private - */ - - Socket.prototype.onError = function (err) { - if (err && err.advice) { - if (err.advice === 'reconnect' && this.connected) { - this.disconnect(); - this.reconnect(); - } - } - - this.publish('error', err && err.reason ? err.reason : err); - }; - - /** - * Called when the transport disconnects. - * - * @api private - */ - - Socket.prototype.onDisconnect = function (reason) { - var wasConnected = this.connected; - - this.connected = false; - this.connecting = false; - this.open = false; - - if (wasConnected) { - this.transport.close(); - this.transport.clearTimeouts(); - this.publish('disconnect', reason); - - if ('booted' != reason && this.options.reconnect && !this.reconnecting) { - this.reconnect(); - } - } - }; - - /** - * Called upon reconnection. - * - * @api private - */ - - Socket.prototype.reconnect = function () { - this.reconnecting = true; - this.reconnectionAttempts = 0; - this.reconnectionDelay = this.options['reconnection delay']; - - var self = this - , maxAttempts = this.options['max reconnection attempts'] - , tryMultiple = this.options['try multiple transports'] - , limit = this.options['reconnection limit']; - - function reset () { - if (self.connected) { - for (var i in self.namespaces) { - if (self.namespaces.hasOwnProperty(i) && '' !== i) { - self.namespaces[i].packet({ type: 'connect' }); - } - } - self.publish('reconnect', self.transport.name, self.reconnectionAttempts); - } - - self.removeListener('connect_failed', maybeReconnect); - self.removeListener('connect', maybeReconnect); - - self.reconnecting = false; - - delete self.reconnectionAttempts; - delete self.reconnectionDelay; - delete self.reconnectionTimer; - delete self.redoTransports; - - self.options['try multiple transports'] = tryMultiple; - }; - - function maybeReconnect () { - if (!self.reconnecting) { - return; - } - - if (self.connected) { - return reset(); - }; - - if (self.connecting && self.reconnecting) { - return self.reconnectionTimer = setTimeout(maybeReconnect, 1000); - } - - if (self.reconnectionAttempts++ >= maxAttempts) { - if (!self.redoTransports) { - self.on('connect_failed', maybeReconnect); - self.options['try multiple transports'] = true; - self.transport = self.getTransport(); - self.redoTransports = true; - self.connect(); - } else { - self.publish('reconnect_failed'); - reset(); - } - } else { - if (self.reconnectionDelay < limit) { - self.reconnectionDelay *= 2; // exponential back off - } - - self.connect(); - self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts); - self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay); - } - }; - - this.options['try multiple transports'] = false; - this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay); - - this.on('connect', maybeReconnect); - }; - -})( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this -); -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.SocketNamespace = SocketNamespace; - - /** - * Socket namespace constructor. - * - * @constructor - * @api public - */ - - function SocketNamespace (socket, name) { - this.socket = socket; - this.name = name || ''; - this.flags = {}; - this.json = new Flag(this, 'json'); - this.ackPackets = 0; - this.acks = {}; - }; - - /** - * Apply EventEmitter mixin. - */ - - io.util.mixin(SocketNamespace, io.EventEmitter); - - /** - * Copies emit since we override it - * - * @api private - */ - - SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit; - - /** - * Creates a new namespace, by proxying the request to the socket. This - * allows us to use the synax as we do on the server. - * - * @api public - */ - - SocketNamespace.prototype.of = function () { - return this.socket.of.apply(this.socket, arguments); - }; - - /** - * Sends a packet. - * - * @api private - */ - - SocketNamespace.prototype.packet = function (packet) { - packet.endpoint = this.name; - this.socket.packet(packet); - this.flags = {}; - return this; - }; - - /** - * Sends a message - * - * @api public - */ - - SocketNamespace.prototype.send = function (data, fn) { - var packet = { - type: this.flags.json ? 'json' : 'message' - , data: data - }; - - if ('function' == typeof fn) { - packet.id = ++this.ackPackets; - packet.ack = true; - this.acks[packet.id] = fn; - } - - return this.packet(packet); - }; - - /** - * Emits an event - * - * @api public - */ - - SocketNamespace.prototype.emit = function (name) { - var args = Array.prototype.slice.call(arguments, 1) - , lastArg = args[args.length - 1] - , packet = { - type: 'event' - , name: name - }; - - if ('function' == typeof lastArg) { - packet.id = ++this.ackPackets; - packet.ack = 'data'; - this.acks[packet.id] = lastArg; - args = args.slice(0, args.length - 1); - } - - packet.args = args; - - return this.packet(packet); - }; - - /** - * Disconnects the namespace - * - * @api private - */ - - SocketNamespace.prototype.disconnect = function () { - if (this.name === '') { - this.socket.disconnect(); - } else { - this.packet({ type: 'disconnect' }); - this.$emit('disconnect'); - } - - return this; - }; - - /** - * Handles a packet - * - * @api private - */ - - SocketNamespace.prototype.onPacket = function (packet) { - var self = this; - - function ack () { - self.packet({ - type: 'ack' - , args: io.util.toArray(arguments) - , ackId: packet.id - }); - }; - - switch (packet.type) { - case 'connect': - this.$emit('connect'); - break; - - case 'disconnect': - if (this.name === '') { - this.socket.onDisconnect(packet.reason || 'booted'); - } else { - this.$emit('disconnect', packet.reason); - } - break; - - case 'message': - case 'json': - var params = ['message', packet.data]; - - if (packet.ack == 'data') { - params.push(ack); - } else if (packet.ack) { - this.packet({ type: 'ack', ackId: packet.id }); - } - - this.$emit.apply(this, params); - break; - - case 'event': - var params = [packet.name].concat(packet.args); - - if (packet.ack == 'data') - params.push(ack); - - this.$emit.apply(this, params); - break; - - case 'ack': - if (this.acks[packet.ackId]) { - this.acks[packet.ackId].apply(this, packet.args); - delete this.acks[packet.ackId]; - } - break; - - case 'error': - if (packet.advice){ - this.socket.onError(packet); - } else { - if (packet.reason == 'unauthorized') { - this.$emit('connect_failed', packet.reason); - } else { - this.$emit('error', packet.reason); - } - } - break; - } - }; - - /** - * Flag interface. - * - * @api private - */ - - function Flag (nsp, name) { - this.namespace = nsp; - this.name = name; - }; - - /** - * Send a message - * - * @api public - */ - - Flag.prototype.send = function () { - this.namespace.flags[this.name] = true; - this.namespace.send.apply(this.namespace, arguments); - }; - - /** - * Emit an event - * - * @api public - */ - - Flag.prototype.emit = function () { - this.namespace.flags[this.name] = true; - this.namespace.emit.apply(this.namespace, arguments); - }; - -})( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.websocket = WS; - - /** - * Detect WebSocket implementation. - */ - - function detectWebSocket () { - if (typeof window != 'undefined') { - return window.WebSocket || window.MozWebSocket; - } - } - - /** - * The WebSocket transport uses the HTML5 WebSocket API to establish an - * persistent connection with the Socket.IO server. This transport will also - * be inherited by the FlashSocket fallback as it provides a API compatible - * polyfill for the WebSockets. - * - * @constructor - * @extends {io.Transport} - * @api public - */ - - function WS (socket) { - io.Transport.apply(this, arguments); - }; - - /** - * Inherits from Transport. - */ - - io.util.inherit(WS, io.Transport); - - /** - * Transport name - * - * @api public - */ - - WS.prototype.name = 'websocket'; - - /** - * Initializes a new `WebSocket` connection with the Socket.IO server. We attach - * all the appropriate listeners to handle the responses from the server. - * - * @returns {Transport} - * @api public - */ - - WS.prototype.open = function () { - var self = this - , query = io.util.query(this.socket.options.query); - - this.websocket = new (detectWebSocket())(this.prepareUrl() + query); - - var self = this; - this.websocket.onopen = function () { - self.onOpen(); - self.socket.setBuffer(false); - }; - this.websocket.onmessage = function (ev) { - self.onData(ev.data); - }; - this.websocket.onclose = function () { - self.onClose(); - self.socket.setBuffer(true); - }; - this.websocket.onerror = function (e) { - self.onError(e); - }; - - return this; - }; - - /** - * Send a message to the Socket.IO server. The message will automatically be - * encoded in the correct message format. - * - * @returns {Transport} - * @api public - */ - - WS.prototype.send = function (data) { - this.websocket.send(data); - return this; - }; - - /** - * Payload - * - * @api private - */ - - WS.prototype.payload = function (arr) { - for (var i = 0, l = arr.length; i < l; i++) { - this.packet(arr[i]); - } - return this; - }; - - /** - * Disconnect the established `WebSocket` connection. - * - * @returns {Transport} - * @api public - */ - - WS.prototype.close = function () { - this.websocket.close(); - return this; - }; - - /** - * Handle the errors that `WebSocket` might be giving when we - * are attempting to connect or send messages. - * - * @param {Error} e The error. - * @api private - */ - - WS.prototype.onError = function (e) { - this.socket.onError(e); - }; - - /** - * Returns the appropriate scheme for the URI generation. - * - * @api private - */ - WS.prototype.scheme = function () { - return this.socket.options.secure ? 'wss' : 'ws'; - }; - - /** - * Checks if the browser has support for native `WebSockets` and that - * it's not the polyfill created for the FlashSocket transport. - * - * @return {Boolean} - * @api public - */ - - WS.check = function () { - var WebSocket = detectWebSocket(); - return WebSocket && !WebSocket.__addTask; - }; - - /** - * Check if the `WebSocket` transport support cross domain communications. - * - * @returns {Boolean} - * @api public - */ - - WS.xdomainCheck = function () { - return true; - }; - - /** - * Add the transport to your public io.transports array. - * - * @api private - */ - - io.transports.push('websocket'); - -})( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.flashsocket = Flashsocket; - - /** - * The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket - * specification. It uses a .swf file to communicate with the server. If you want - * to serve the .swf file from a other server than where the Socket.IO script is - * coming from you need to use the insecure version of the .swf. More information - * about this can be found on the github page. - * - * @constructor - * @extends {io.Transport.websocket} - * @api public - */ - - function Flashsocket () { - io.Transport.websocket.apply(this, arguments); - }; - - /** - * Inherits from Transport. - */ - - io.util.inherit(Flashsocket, io.Transport.websocket); - - /** - * Transport name - * - * @api public - */ - - Flashsocket.prototype.name = 'flashsocket'; - - /** - *Disconnect the established `FlashSocket` connection. This is done by adding a - * new task to the FlashSocket. The rest will be handled off by the `WebSocket` - * transport. - * - * @returns {Transport} - * @api public - */ - - Flashsocket.prototype.open = function () { - var self = this - , args = arguments; - - WebSocket.__addTask(function () { - io.Transport.websocket.prototype.open.apply(self, args); - }); - return this; - }; - - /** - * Sends a message to the Socket.IO server. This is done by adding a new - * task to the FlashSocket. The rest will be handled off by the `WebSocket` - * transport. - * - * @returns {Transport} - * @api public - */ - - Flashsocket.prototype.send = function () { - var self = this, args = arguments; - WebSocket.__addTask(function () { - io.Transport.websocket.prototype.send.apply(self, args); - }); - return this; - }; - - /** - * Disconnects the established `FlashSocket` connection. - * - * @returns {Transport} - * @api public - */ - - Flashsocket.prototype.close = function () { - WebSocket.__tasks.length = 0; - io.Transport.websocket.prototype.close.call(this); - return this; - }; - - /** - * The WebSocket fall back needs to append the flash container to the body - * element, so we need to make sure we have access to it. Or defer the call - * until we are sure there is a body element. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ - - Flashsocket.prototype.ready = function (socket, fn) { - function init () { - var options = socket.options - , path = [ - 'http' + (options.secure ? 's' : '') + ':/' - , options.host + ':' + options.port - , options.resource - , 'static/flashsocket' - , 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf' - ]; - - // Only start downloading the swf file when the checked that this browser - // actually supports it - if (!Flashsocket.loaded) { - if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') { - // Set the correct file based on the XDomain settings - WEB_SOCKET_SWF_LOCATION = path.join('/'); - } - - WebSocket.__initialize(); - Flashsocket.loaded = true; - } - - fn.call(self); - } - - var self = this; - if (document.body) return init(); - - io.util.load(init); - }; - - /** - * Check if the FlashSocket transport is supported as it requires that the Adobe - * Flash Player plug-in version `10.0.0` or greater is installed. And also check if - * the polyfill is correctly loaded. - * - * @returns {Boolean} - * @api public - */ - - Flashsocket.check = function () { - if ( - typeof WebSocket == 'undefined' - || !('__initialize' in WebSocket) || !swfobject - ) return false; - - return swfobject.getFlashPlayerVersion().major >= 1; - }; - - /** - * Check if the FlashSocket transport can be used as cross domain / cross origin - * transport. Because we can't see which type (secure or insecure) of .swf is used - * we will just return true. - * - * @returns {Boolean} - * @api public - */ - - Flashsocket.xdomainCheck = function () { - return true; - }; - - /** - * Disable AUTO_INITIALIZATION - */ - - if (typeof window != 'undefined') { - WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true; - } - - /** - * Add the transport to your public io.transports array. - * - * @api private - */ - - io.transports.push('flashsocket'); -})( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); -/* SWFObject v2.2 - is released under the MIT License -*/ -var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab -// License: New BSD License -// Reference: http://dev.w3.org/html5/websockets/ -// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol - -(function() { - - if (window.WebSocket) return; - - var console = window.console; - if (!console || !console.log || !console.error) { - console = {log: function(){ }, error: function(){ }}; - } - - if (!swfobject.hasFlashPlayerVersion("10.0.0")) { - console.error("Flash Player >= 10.0.0 is required."); - return; - } - if (location.protocol == "file:") { - console.error( - "WARNING: web-socket-js doesn't work in file:///... URL " + - "unless you set Flash Security Settings properly. " + - "Open the page via Web server i.e. http://..."); - } - - /** - * This class represents a faux web socket. - * @param {string} url - * @param {array or string} protocols - * @param {string} proxyHost - * @param {int} proxyPort - * @param {string} headers - */ - WebSocket = function(url, protocols, proxyHost, proxyPort, headers) { - var self = this; - self.__id = WebSocket.__nextId++; - WebSocket.__instances[self.__id] = self; - self.readyState = WebSocket.CONNECTING; - self.bufferedAmount = 0; - self.__events = {}; - if (!protocols) { - protocols = []; - } else if (typeof protocols == "string") { - protocols = [protocols]; - } - // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc. - // Otherwise, when onopen fires immediately, onopen is called before it is set. - setTimeout(function() { - WebSocket.__addTask(function() { - WebSocket.__flash.create( - self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null); - }); - }, 0); - }; - - /** - * Send data to the web socket. - * @param {string} data The data to send to the socket. - * @return {boolean} True for success, false for failure. - */ - WebSocket.prototype.send = function(data) { - if (this.readyState == WebSocket.CONNECTING) { - throw "INVALID_STATE_ERR: Web Socket connection has not been established"; - } - // We use encodeURIComponent() here, because FABridge doesn't work if - // the argument includes some characters. We don't use escape() here - // because of this: - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions - // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't - // preserve all Unicode characters either e.g. "\uffff" in Firefox. - // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require - // additional testing. - var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data)); - if (result < 0) { // success - return true; - } else { - this.bufferedAmount += result; - return false; - } - }; - - /** - * Close this web socket gracefully. - */ - WebSocket.prototype.close = function() { - if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) { - return; - } - this.readyState = WebSocket.CLOSING; - WebSocket.__flash.close(this.__id); - }; - - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {string} type - * @param {function} listener - * @param {boolean} useCapture - * @return void - */ - WebSocket.prototype.addEventListener = function(type, listener, useCapture) { - if (!(type in this.__events)) { - this.__events[type] = []; - } - this.__events[type].push(listener); - }; - - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {string} type - * @param {function} listener - * @param {boolean} useCapture - * @return void - */ - WebSocket.prototype.removeEventListener = function(type, listener, useCapture) { - if (!(type in this.__events)) return; - var events = this.__events[type]; - for (var i = events.length - 1; i >= 0; --i) { - if (events[i] === listener) { - events.splice(i, 1); - break; - } - } - }; - - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {Event} event - * @return void - */ - WebSocket.prototype.dispatchEvent = function(event) { - var events = this.__events[event.type] || []; - for (var i = 0; i < events.length; ++i) { - events[i](event); - } - var handler = this["on" + event.type]; - if (handler) handler(event); - }; - - /** - * Handles an event from Flash. - * @param {Object} flashEvent - */ - WebSocket.prototype.__handleEvent = function(flashEvent) { - if ("readyState" in flashEvent) { - this.readyState = flashEvent.readyState; - } - if ("protocol" in flashEvent) { - this.protocol = flashEvent.protocol; - } - - var jsEvent; - if (flashEvent.type == "open" || flashEvent.type == "error") { - jsEvent = this.__createSimpleEvent(flashEvent.type); - } else if (flashEvent.type == "close") { - // TODO implement jsEvent.wasClean - jsEvent = this.__createSimpleEvent("close"); - } else if (flashEvent.type == "message") { - var data = decodeURIComponent(flashEvent.message); - jsEvent = this.__createMessageEvent("message", data); - } else { - throw "unknown event type: " + flashEvent.type; - } - - this.dispatchEvent(jsEvent); - }; - - WebSocket.prototype.__createSimpleEvent = function(type) { - if (document.createEvent && window.Event) { - var event = document.createEvent("Event"); - event.initEvent(type, false, false); - return event; - } else { - return {type: type, bubbles: false, cancelable: false}; - } - }; - - WebSocket.prototype.__createMessageEvent = function(type, data) { - if (document.createEvent && window.MessageEvent && !window.opera) { - var event = document.createEvent("MessageEvent"); - event.initMessageEvent("message", false, false, data, null, null, window, null); - return event; - } else { - // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes. - return {type: type, data: data, bubbles: false, cancelable: false}; - } - }; - - /** - * Define the WebSocket readyState enumeration. - */ - WebSocket.CONNECTING = 0; - WebSocket.OPEN = 1; - WebSocket.CLOSING = 2; - WebSocket.CLOSED = 3; - - WebSocket.__flash = null; - WebSocket.__instances = {}; - WebSocket.__tasks = []; - WebSocket.__nextId = 0; - - /** - * Load a new flash security policy file. - * @param {string} url - */ - WebSocket.loadFlashPolicyFile = function(url){ - WebSocket.__addTask(function() { - WebSocket.__flash.loadManualPolicyFile(url); - }); - }; - - /** - * Loads WebSocketMain.swf and creates WebSocketMain object in Flash. - */ - WebSocket.__initialize = function() { - if (WebSocket.__flash) return; - - if (WebSocket.__swfLocation) { - // For backword compatibility. - window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation; - } - if (!window.WEB_SOCKET_SWF_LOCATION) { - console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf"); - return; - } - var container = document.createElement("div"); - container.id = "webSocketContainer"; - // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents - // Flash from loading at least in IE. So we move it out of the screen at (-100, -100). - // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash - // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is - // the best we can do as far as we know now. - container.style.position = "absolute"; - if (WebSocket.__isFlashLite()) { - container.style.left = "0px"; - container.style.top = "0px"; - } else { - container.style.left = "-100px"; - container.style.top = "-100px"; - } - var holder = document.createElement("div"); - holder.id = "webSocketFlash"; - container.appendChild(holder); - document.body.appendChild(container); - // See this article for hasPriority: - // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html - swfobject.embedSWF( - WEB_SOCKET_SWF_LOCATION, - "webSocketFlash", - "1" /* width */, - "1" /* height */, - "10.0.0" /* SWF version */, - null, - null, - {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"}, - null, - function(e) { - if (!e.success) { - console.error("[WebSocket] swfobject.embedSWF failed"); - } - }); - }; - - /** - * Called by Flash to notify JS that it's fully loaded and ready - * for communication. - */ - WebSocket.__onFlashInitialized = function() { - // We need to set a timeout here to avoid round-trip calls - // to flash during the initialization process. - setTimeout(function() { - WebSocket.__flash = document.getElementById("webSocketFlash"); - WebSocket.__flash.setCallerUrl(location.href); - WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG); - for (var i = 0; i < WebSocket.__tasks.length; ++i) { - WebSocket.__tasks[i](); - } - WebSocket.__tasks = []; - }, 0); - }; - - /** - * Called by Flash to notify WebSockets events are fired. - */ - WebSocket.__onFlashEvent = function() { - setTimeout(function() { - try { - // Gets events using receiveEvents() instead of getting it from event object - // of Flash event. This is to make sure to keep message order. - // It seems sometimes Flash events don't arrive in the same order as they are sent. - var events = WebSocket.__flash.receiveEvents(); - for (var i = 0; i < events.length; ++i) { - WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]); - } - } catch (e) { - console.error(e); - } - }, 0); - return true; - }; - - // Called by Flash. - WebSocket.__log = function(message) { - console.log(decodeURIComponent(message)); - }; - - // Called by Flash. - WebSocket.__error = function(message) { - console.error(decodeURIComponent(message)); - }; - - WebSocket.__addTask = function(task) { - if (WebSocket.__flash) { - task(); - } else { - WebSocket.__tasks.push(task); - } - }; - - /** - * Test if the browser is running flash lite. - * @return {boolean} True if flash lite is running, false otherwise. - */ - WebSocket.__isFlashLite = function() { - if (!window.navigator || !window.navigator.mimeTypes) { - return false; - } - var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"]; - if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) { - return false; - } - return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false; - }; - - if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) { - if (window.addEventListener) { - window.addEventListener("load", function(){ - WebSocket.__initialize(); - }, false); - } else { - window.attachEvent("onload", function(){ - WebSocket.__initialize(); - }); - } - } - -})(); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io, global) { - - /** - * Expose constructor. - * - * @api public - */ - - exports.XHR = XHR; - - /** - * XHR constructor - * - * @costructor - * @api public - */ - - function XHR (socket) { - if (!socket) return; - - io.Transport.apply(this, arguments); - this.sendBuffer = []; - }; - - /** - * Inherits from Transport. - */ - - io.util.inherit(XHR, io.Transport); - - /** - * Establish a connection - * - * @returns {Transport} - * @api public - */ - - XHR.prototype.open = function () { - this.socket.setBuffer(false); - this.onOpen(); - this.get(); - - // we need to make sure the request succeeds since we have no indication - // whether the request opened or not until it succeeded. - this.setCloseTimeout(); - - return this; - }; - - /** - * Check if we need to send data to the Socket.IO server, if we have data in our - * buffer we encode it and forward it to the `post` method. - * - * @api private - */ - - XHR.prototype.payload = function (payload) { - var msgs = []; - - for (var i = 0, l = payload.length; i < l; i++) { - msgs.push(io.parser.encodePacket(payload[i])); - } - - this.send(io.parser.encodePayload(msgs)); - }; - - /** - * Send data to the Socket.IO server. - * - * @param data The message - * @returns {Transport} - * @api public - */ - - XHR.prototype.send = function (data) { - this.post(data); - return this; - }; - - /** - * Posts a encoded message to the Socket.IO server. - * - * @param {String} data A encoded message. - * @api private - */ - - function empty () { }; - - XHR.prototype.post = function (data) { - var self = this; - this.socket.setBuffer(true); - - function stateChange () { - if (this.readyState == 4) { - this.onreadystatechange = empty; - self.posting = false; - - if (this.status == 200){ - self.socket.setBuffer(false); - } else { - self.onClose(); - } - } - } - - function onload () { - this.onload = empty; - self.socket.setBuffer(false); - }; - - this.sendXHR = this.request('POST'); - - if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) { - this.sendXHR.onload = this.sendXHR.onerror = onload; - } else { - this.sendXHR.onreadystatechange = stateChange; - } - - this.sendXHR.send(data); - }; - - /** - * Disconnects the established `XHR` connection. - * - * @returns {Transport} - * @api public - */ - - XHR.prototype.close = function () { - this.onClose(); - return this; - }; - - /** - * Generates a configured XHR request - * - * @param {String} url The url that needs to be requested. - * @param {String} method The method the request should use. - * @returns {XMLHttpRequest} - * @api private - */ - - XHR.prototype.request = function (method) { - var req = io.util.request(this.socket.isXDomain()) - , query = io.util.query(this.socket.options.query, 't=' + +new Date); - - req.open(method || 'GET', this.prepareUrl() + query, true); - - if (method == 'POST') { - try { - if (req.setRequestHeader) { - req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); - } else { - // XDomainRequest - req.contentType = 'text/plain'; - } - } catch (e) {} - } - - return req; - }; - - /** - * Returns the scheme to use for the transport URLs. - * - * @api private - */ - - XHR.prototype.scheme = function () { - return this.socket.options.secure ? 'https' : 'http'; - }; - - /** - * Check if the XHR transports are supported - * - * @param {Boolean} xdomain Check if we support cross domain requests. - * @returns {Boolean} - * @api public - */ - - XHR.check = function (socket, xdomain) { - try { - if (io.util.request(xdomain)) { - return true; - } - } catch(e) {} - - return false; - }; - - /** - * Check if the XHR transport supports corss domain requests. - * - * @returns {Boolean} - * @api public - */ - - XHR.xdomainCheck = function () { - return XHR.check(null, true); - }; - -})( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports.htmlfile = HTMLFile; - - /** - * The HTMLFile transport creates a `forever iframe` based transport - * for Internet Explorer. Regular forever iframe implementations will - * continuously trigger the browsers buzy indicators. If the forever iframe - * is created inside a `htmlfile` these indicators will not be trigged. - * - * @constructor - * @extends {io.Transport.XHR} - * @api public - */ - - function HTMLFile (socket) { - io.Transport.XHR.apply(this, arguments); - }; - - /** - * Inherits from XHR transport. - */ - - io.util.inherit(HTMLFile, io.Transport.XHR); - - /** - * Transport name - * - * @api public - */ - - HTMLFile.prototype.name = 'htmlfile'; - - /** - * Creates a new ActiveX `htmlfile` with a forever loading iframe - * that can be used to listen to messages. Inside the generated - * `htmlfile` a reference will be made to the HTMLFile transport. - * - * @api private - */ - - HTMLFile.prototype.get = function () { - this.doc = new ActiveXObject('htmlfile'); - this.doc.open(); - this.doc.write(''); - this.doc.close(); - this.doc.parentWindow.s = this; - - var iframeC = this.doc.createElement('div'); - iframeC.className = 'socketio'; - - this.doc.body.appendChild(iframeC); - this.iframe = this.doc.createElement('iframe'); - - iframeC.appendChild(this.iframe); - - var self = this - , query = io.util.query(this.socket.options.query, 't='+ +new Date); - - this.iframe.src = this.prepareUrl() + query; - - io.util.on(window, 'unload', function () { - self.destroy(); - }); - }; - - /** - * The Socket.IO server will write script tags inside the forever - * iframe, this function will be used as callback for the incoming - * information. - * - * @param {String} data The message - * @param {document} doc Reference to the context - * @api private - */ - - HTMLFile.prototype._ = function (data, doc) { - this.onData(data); - try { - var script = doc.getElementsByTagName('script')[0]; - script.parentNode.removeChild(script); - } catch (e) { } - }; - - /** - * Destroy the established connection, iframe and `htmlfile`. - * And calls the `CollectGarbage` function of Internet Explorer - * to release the memory. - * - * @api private - */ - - HTMLFile.prototype.destroy = function () { - if (this.iframe){ - try { - this.iframe.src = 'about:blank'; - } catch(e){} - - this.doc = null; - this.iframe.parentNode.removeChild(this.iframe); - this.iframe = null; - - CollectGarbage(); - } - }; - - /** - * Disconnects the established connection. - * - * @returns {Transport} Chaining. - * @api public - */ - - HTMLFile.prototype.close = function () { - this.destroy(); - return io.Transport.XHR.prototype.close.call(this); - }; - - /** - * Checks if the browser supports this transport. The browser - * must have an `ActiveXObject` implementation. - * - * @return {Boolean} - * @api public - */ - - HTMLFile.check = function () { - if ('ActiveXObject' in window){ - try { - var a = new ActiveXObject('htmlfile'); - return a && io.Transport.XHR.check(); - } catch(e){} - } - return false; - }; - - /** - * Check if cross domain requests are supported. - * - * @returns {Boolean} - * @api public - */ - - HTMLFile.xdomainCheck = function () { - // we can probably do handling for sub-domains, we should - // test that it's cross domain but a subdomain here - return false; - }; - - /** - * Add the transport to your public io.transports array. - * - * @api private - */ - - io.transports.push('htmlfile'); - -})( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io, global) { - - /** - * Expose constructor. - */ - - exports['xhr-polling'] = XHRPolling; - - /** - * The XHR-polling transport uses long polling XHR requests to create a - * "persistent" connection with the server. - * - * @constructor - * @api public - */ - - function XHRPolling () { - io.Transport.XHR.apply(this, arguments); - }; - - /** - * Inherits from XHR transport. - */ - - io.util.inherit(XHRPolling, io.Transport.XHR); - - /** - * Merge the properties from XHR transport - */ - - io.util.merge(XHRPolling, io.Transport.XHR); - - /** - * Transport name - * - * @api public - */ - - XHRPolling.prototype.name = 'xhr-polling'; - - /** - * Establish a connection, for iPhone and Android this will be done once the page - * is loaded. - * - * @returns {Transport} Chaining. - * @api public - */ - - XHRPolling.prototype.open = function () { - var self = this; - - io.Transport.XHR.prototype.open.call(self); - return false; - }; - - /** - * Starts a XHR request to wait for incoming messages. - * - * @api private - */ - - function empty () {}; - - XHRPolling.prototype.get = function () { - if (!this.open) return; - - var self = this; - - function stateChange () { - if (this.readyState == 4) { - this.onreadystatechange = empty; - - if (this.status == 200) { - self.onData(this.responseText); - self.get(); - } else { - self.onClose(); - } - } - }; - - function onload () { - this.onload = empty; - self.onData(this.responseText); - self.get(); - }; - - this.xhr = this.request(); - - if (global.XDomainRequest && this.xhr instanceof XDomainRequest) { - this.xhr.onload = this.xhr.onerror = onload; - } else { - this.xhr.onreadystatechange = stateChange; - } - - this.xhr.send(null); - }; - - /** - * Handle the unclean close behavior. - * - * @api private - */ - - XHRPolling.prototype.onClose = function () { - io.Transport.XHR.prototype.onClose.call(this); - - if (this.xhr) { - this.xhr.onreadystatechange = this.xhr.onload = empty; - try { - this.xhr.abort(); - } catch(e){} - this.xhr = null; - } - }; - - /** - * Webkit based browsers show a infinit spinner when you start a XHR request - * before the browsers onload event is called so we need to defer opening of - * the transport until the onload event is called. Wrapping the cb in our - * defer method solve this. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ - - XHRPolling.prototype.ready = function (socket, fn) { - var self = this; - - io.util.defer(function () { - fn.call(self); - }); - }; - - /** - * Add the transport to your public io.transports array. - * - * @api private - */ - - io.transports.push('xhr-polling'); - -})( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this -); - -/** - * socket.io - * Copyright(c) 2011 LearnBoost - * MIT Licensed - */ - -(function (exports, io) { - - /** - * Expose constructor. - */ - - exports['jsonp-polling'] = JSONPPolling; - - /** - * The JSONP transport creates an persistent connection by dynamically - * inserting a script tag in the page. This script tag will receive the - * information of the Socket.IO server. When new information is received - * it creates a new script tag for the new data stream. - * - * @constructor - * @extends {io.Transport.xhr-polling} - * @api public - */ - - function JSONPPolling (socket) { - io.Transport['xhr-polling'].apply(this, arguments); - - this.index = io.j.length; - - var self = this; - - io.j.push(function (msg) { - self._(msg); - }); - }; - - /** - * Inherits from XHR polling transport. - */ - - io.util.inherit(JSONPPolling, io.Transport['xhr-polling']); - - /** - * Transport name - * - * @api public - */ - - JSONPPolling.prototype.name = 'jsonp-polling'; - - /** - * Posts a encoded message to the Socket.IO server using an iframe. - * The iframe is used because script tags can create POST based requests. - * The iframe is positioned outside of the view so the user does not - * notice it's existence. - * - * @param {String} data A encoded message. - * @api private - */ - - JSONPPolling.prototype.post = function (data) { - var self = this - , query = io.util.query( - this.socket.options.query - , 't='+ (+new Date) + '&i=' + this.index - ); - - if (!this.form) { - var form = document.createElement('FORM') - , area = document.createElement('TEXTAREA') - , id = this.iframeId = 'socketio_iframe_' + this.index - , iframe; - - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); - - this.form = form; - this.area = area; - } - - this.form.action = this.prepareUrl() + query; - - function complete () { - initIframe(); - self.socket.setBuffer(false); - }; - - function initIframe () { - if (self.iframe) { - self.form.removeChild(self.iframe); - } - - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - iframe = document.createElement('