# Server

ws4py comes with a few server implementations built around the main `WebSocket` class.

## CherryPy

ws4py provides an extension to CherryPy 3 to enable WebSocket from the framework layer. It is based on the CherryPy plugin and tool mechanisms.

The `WebSocket tool` plays at the request level on every request received by the server. Its goal is to perform the WebSocket handshake and, if it succeeds, to create the `WebSocket` instance (well a subclass you will be implementing) and push it to the plugin.

The `WebSocket plugin` works at the CherryPy system level and has a single instance throughout. Its goal is to track websocket instances created by the tool and free their resources when connections are closed.

Here is a simple example of an echo server:

     1import cherrypy
     2from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
     3from ws4py.websocket import EchoWebSocket
     4
     5cherrypy.config.update({'server.socket_port': 9000})
     6WebSocketPlugin(cherrypy.engine).subscribe()
     7cherrypy.tools.websocket = WebSocketTool()
     8
     9class Root(object):
    10    @cherrypy.expose
    11    def index(self):
    12        return 'some HTML with a websocket javascript connection'
    13
    14    @cherrypy.expose
    15    def ws(self):
    16        # you can access the class instance through
    17        handler = cherrypy.request.ws_handler
    18
    19cherrypy.quickstart(Root(), '/', config={'/ws': {'tools.websocket.on': True,
    20                                                 'tools.websocket.handler_cls': EchoWebSocket}})

Note how we specify the class which should be instanciated by the server on each connection. The great aspect of the tool mechanism is that you can specify a different class on a per-path basis.

## gevent

gevent is a coroutine, called greenlets, implementation for very concurrent applications. ws4py offers a server implementation for this library on top of the WSGI protocol. Using it is as simple as:

    1from gevent import monkey; monkey.patch_all()
    2from ws4py.websocket import EchoWebSocket
    3from ws4py.server.geventserver import WSGIServer
    4from ws4py.server.wsgiutils import WebSocketWSGIApplication
    5
    6server = WSGIServer(('localhost', 9000), WebSocketWSGIApplication(handler_cls=EchoWebSocket))
    7server.serve_forever()

First we patch all the standard modules so that the stdlib runs well with as gevent. Then we simply create a WSGI server and specify the class which will be instanciated internally each time a connection is successful.

## wsgiref

`wsgiref` is a built-in WSGI package that provides various classes and helpers to develop against WSGI. Mostly it provides a basic WSGI server that can be usedfor testing or simple demos. ws4py provides support for websocket on wsgiref for testing purpose as well. It’s not meant to be used in production, since it can only initiate web socket connections one at a time, as a result of being single threaded. However, once accepted, ws4py takes over, which is multithreaded by default.

     1from wsgiref.simple_server import make_server
     2from ws4py.websocket import EchoWebSocket
     3from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
     4from ws4py.server.wsgiutils import WebSocketWSGIApplication
     5
     6server = make_server('', 9000, server_class=WSGIServer,
     7                     handler_class=WebSocketWSGIRequestHandler,
     8                     app=WebSocketWSGIApplication(handler_cls=EchoWebSocket))
     9server.initialize_websockets_manager()
    10server.serve_forever()

## asyncio

`asyncio` is the implementation of PEP 3156, the new asynchronous framework for concurrent applications.

     1from ws4py.async_websocket import EchoWebSocket
     2
     3loop = asyncio.get_event_loop()
     4
     5def start_server():
     6    proto_factory = lambda: WebSocketProtocol(EchoWebSocket)
     7    return loop.create_server(proto_factory, '', 9007)
     8
     9s = loop.run_until_complete(start_server())
    10print('serving on', s.sockets[0].getsockname())
    11loop.run_forever()

Warning

The provided HTTP server used for the handshake is clearly not production ready. However, once the handshake is performed, the rest of the code runs the same stack as the other server implementations. It should be easy to replace the HTTP interface with any asyncio aware HTTP framework.