Git Product home page Git Product logo

simple-websocket-server's Introduction

A simple WebSocket server

GitHub Actions PyPI PyPI - Python Version PyPI - License

Based on simple-websocket-server.

  • RFC 6455 (All latest browsers)
  • TLS/SSL out of the box
  • Passes Autobahns Websocket Testsuite
  • Support for Python 2 and 3

Installation

pip install simple-websocket-server

Echo Server Example

from simple_websocket_server import WebSocketServer, WebSocket


class SimpleEcho(WebSocket):
    def handle(self):
        # echo message back to client
        self.send_message(self.data)

    def connected(self):
        print(self.address, 'connected')

    def handle_close(self):
        print(self.address, 'closed')


server = WebSocketServer('', 8000, SimpleEcho)
server.serve_forever()

Open tests/websocket.html and connect to the server.

Chat Server Example

from simple_websocket_server import WebSocketServer, WebSocket


class SimpleChat(WebSocket):
    def handle(self):
        for client in clients:
            if client != self:
                client.send_message(self.address[0] + u' - ' + self.data)

    def connected(self):
        print(self.address, 'connected')
        for client in clients:
            client.send_message(self.address[0] + u' - connected')
        clients.append(self)

    def handle_close(self):
        clients.remove(self)
        print(self.address, 'closed')
        for client in clients:
            client.send_message(self.address[0] + u' - disconnected')


clients = []

server = WebSocketServer('', 8000, SimpleChat)
server.serve_forever()

Open multiple tests/websocket.html and connect to the server.

Want to get up and running faster?

There is an example which provides a simple echo and chat server

Echo Server

python tests/example_server.py --example echo

Chat Server (open up multiple tests/websocket.html files)

python tests/example_server.py --example chat

TLS/SSL Example

  1. Generate a certificate with key

     openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout key.pem
    
  2. Run the secure TLS/SSL server (in this case the cert.pem file is in the same directory)

     python tests/example_server.py --example chat --ssl 1
    
  3. Offer the certificate to the browser by serving tests/websocket.html through https. The HTTPS server will look for cert.pem in the local directory. Ensure the tests/websocket.html is also in the same directory to where the server is run.

     python tests/simple_https_server.py
    
  4. Open a web browser to: https://localhost:443/tests/websocket.html

  5. Change ws://localhost:8000/ to wss://localhost:8000 and click connect.

Note: if you are having problems connecting, ensure that the certificate is added in your browser against the exception https://localhost:8000 or whatever host:port pair you want to connect to.

For the Programmers

connected: called when handshake is complete

  • self.address: TCP address port tuple of the endpoint

handle_close: called when the endpoint is closed or there is an error

  • self.address: TCP address port tuple of the endpoint

handle: gets called when there is an incoming message from the client endpoint

  • self.address: TCP address port tuple of the endpoint
  • self.opcode: the WebSocket frame type (STREAM, TEXT, BINARY)
  • self.data: bytearray (BINARY frame) or unicode string payload (TEXT frame)
  • self.request: HTTP details from the WebSocket handshake (refer to BaseHTTPRequestHandler)

send_message: send some text or binary data to the client endpoint

  • sending data as a unicode object will send a TEXT frame
  • sending data as a bytearray object will send a BINARY frame

close: send close frame to endpoint

Licensing

MIT

simple-websocket-server's People

Contributors

pikhovkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

simple-websocket-server's Issues

Fix your library lol

Functionality works on, Mac OS and Linux.

Server does not run on Windows at all.

This had been tested with and without admin perms and on ports <1024 and >1024

I confirmed this is what is breaking it by testing alternative librarys

I could try and use those library's but this is the most easy to use so I'd rather not have to port my entire program already

So just fix this library please, if u need someone to help test I'll be more than happy to do that

traceback when using library

I am getting this traceback using your sample code running on python 3.5 Windows 7 X64 SP1

Traceback (most recent call last):
  File "C:\Stackless35\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Stackless35\lib\threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Stackless35\lib\site-packages\simple_websocket_server\__init__.py", line 658, in serve_forever
    self.handle_request()
  File "C:\Stackless35\lib\site-packages\simple_websocket_server\__init__.py", line 598, in handle_request
    r_list, w_list, x_list = select(self.listeners, writers, self.listeners, self.selectInterval)
ValueError: file descriptor cannot be a negative integer (-1)

this traceback occurs right away.

Server don't detect forced disconnect

When the client is suddently disconnected (like if his network disconnects or he connects to a VPN while he's connected to the websocket), it will be disconnected from the server (ok) but the server will still think he's still connected...

Any solution to this?

High buffering time

Hello pikhokin,
Thanks for the great implementation of the websocket server. I am facing one issue. It would be great if you could help out. I am streaming base64 image data from the client to thw websocket server. It is observed that the initial delay in the receiving of message is 1s but as the streaming goes on. The delay gets incrementally accumulated to 1min and keeps on increasing. It would be helpful if you could let me know the change which I need to do in the code so that I can get realtime streaming with minimum delay.

Thanks in advance,
Rahul

Browser fails to open 'https://localhost:443/tests/websocket.html'

After following step up to 3 in the section 'TLS/SSL Example'

FIY: both the servers are running i.e.

python tests/simple_https_server.py
and
python tests/example_server.py --example chat --ssl 1

but no response

I also tried to connect wss with ws client (i.e. 'WebSocket Test Client' a google chrome extension)
but it throws 'error'

Someone please guide me on 'how to connect wss client with this server' .......

Can you release 0.4.0?

It would be great if you can release 0.4.0.
This one enables the secure ws (wss://) and thus I need this one. However it is not release so difficult to install without having that revision in pip repo's.

Thanks,
Karel.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.