Git Product home page Git Product logo

simple-websocket-server's People

Contributors

ahadley1124 avatar alexey-v-paramonov avatar belm0 avatar davepallot avatar dennisschulmeister avatar dpallot avatar dyfer avatar geertl avatar junhaoliao avatar kalissar30 avatar koiledlobster avatar larivact avatar lgt1001 avatar lmlsna avatar ojensen5115 avatar szabadkai 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  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  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  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  avatar  avatar

simple-websocket-server's Issues

Run with Python3

I tried to convert the code to Python3 and try running. Having some errors. Can you please implement the same code for Python3

fragment data

hello, the fragmented message in the rfc6455 confused me. Could you please tell me how can i send fragmentd message to server through javascript webscoket client, thanks?

How to send video stream via webrtc to python ?

I want to use JS at front-end and send live stream of video using getUserMedia api to opencv-python at bacl-end for analyzing video and send back data to client. How can I do this using your websocket-server?

ssl.SSLError: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca

Hi, I am trying to run the SimpleHTTPSServer.py, and I have some errors:

First:
this packages have been moved to http.server
import BaseHTTPServer, SimpleHTTPServer
(I've solved this error)

Second:
When I try to run SimpleHTTPSServer, I get this error:

ssl.SSLError: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca

I have generate pem with:
openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem

Exactly how do you tell us. And Its in the right path, but when I run:

sudo python3 SimpleHTTPSServer.py --example chat --ssl 1 --cert ./cert.pem

then show me the ssl error ('unknow ca')

I don't know what I am doing bad, thanks for help.

New feature: Simple HTTP server with websocket support

I think that it's not too difficult to create an HTTP server with websocket support. Maybe reusing some code of the python module SimpleHTTPServer and BaseHTTPServer is possible to do something quick.

With this new feature added it will be possible to create local web servers with websocket support for web desktop applications in Python.

How to stop server properly?

Hello,

I am using this web socket server in a Sublime Text plugin, and I need to stop the server properly once it is not used anymore.

The server is used in a thread, that I can access from anywhere in my plugin. How do I tell it to stop listening?

When I use server.close(), I get this error:

  File "server.py", line 679, in <module>
    server.serveforever()
  File "server.py", line 612, in serveforever
    rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval)

The same thing happens when I just make a simple file and Ctrl+C it from the command line.

What did I do wrong?

License?

There doesn't appear to be a license anywhere in the readme, or in the source code. Could you please clarify the license this source code is provided under?

Thanks.

Delay on sendMessage

When using time.sleep(1) before sendMessage, the hole process stops (even the others connections).
Ex:
def handleConnected(self): print self.address, 'connected' for client in clients: time.sleep(1) client.sendMessage(self.address[0] + u' - connected')

How to solve it?

SSL Chat Server Example.. fail..

echo server pass.. chat server fail..

how do I Broadcast to clients from chat server?

This is the log that server dies when connected in the browser.

Thank you for your help

nvidia@tegra-ubuntu:~/voice/websocket/SimpleWebSocketServer$ python SimpleExampleServer.py --example chat --ssl 1 --cert ./cert.pem
Traceback (most recent call last):
File "SimpleExampleServer.py", line 71, in
server.serveforever()
File "/home/nvidia/voice/websocket/SimpleWebSocketServer/SimpleWebSocketServer.py", line 688, in serveforever
super(SimpleSSLWebSocketServer, self).serveforever()
File "/home/nvidia/voice/websocket/SimpleWebSocketServer/SimpleWebSocketServer.py", line 646, in serveforever
client.handleClose()
File "SimpleExampleServer.py", line 38, in handleClose
clients.remove(self)
ValueError: list.remove(x): x not in list

Can't connect more users

I have something like chat-socket (used chat example + ssl), currently with ~300 active users, problem happens every 1-2 hours. New users can't connect, but it doesnt disconnect already connected users although their messages also don't reach socket "handleMessage" method. Before with few users it also was happening but not so frequently.
In log file I can see only lines like that:

('78.46.227.52', 51444) connected
('78.46.227.52', 51444) closed

How to investigate details of the issue?

No support for sub-protocols

Thanks to this great script, I got a websocket server up and running very quickly, so thank a lot for this!
Unfortunately one of the web clients that needs to connect to this, has a sub-protocol defined when setting up the websocket connection.
Is there any support for this in this websocket server?

100% CPU usage

Steps to reproduce:

strace python SimpleExampleServer.py --example echo

Connect a client, then watch as endless select() calls are made.

WebSocket frozen in SSL after receiving message bigger than MTU

Using the client from https://github.com/websocket-client/websocket-client, and tweaking it so that it send 100 big messages bigger then usual MTU of 1500 bytes, and disabling the SSL certificate check with "sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False}", than running the SimpleExampleServer.py with added debug print in SimpleEcho/handleMessage(), we can see that after awhile, it stop receiving the messages, therefore never echo the remaining ones, sometime only after 9-10 messages, sometimes after 30 or more, but never succeed to 100 messages.

This symptom doesn't seems to happen in Non-SSL.

And also, just to make sure it wasn't a bug of the websocket-client, this one as been tested with wss://echo.websocket.org/ several hundreds times, and didn't get any issue.

I'm not familiar with the low level websocket handshaking, so I didn't figured out where to add some traces to narrow the issue.
Could you provide some help ?

Send message to client without having to receive one first

I'd like to use your websocket implementation but my use-case might be a little weird. Basically I want the webpage to connect to a server started by a script I have that is generating data. As that data is generated, I need to send it to the connected client (there should only ever be one). But from your examples I only see that you can call sendMessage in response to something. I tried to send the server off on it's own thread and call sendMessage from outside of that but it just errors saying that sendMessage is unbound.

Any thoughts?

socket.error: [Errno 48] Address already in use

Running: https://github.com/dpallot/simple-websocket-server/blob/master/SimpleWebSocketServer/SimpleExampleServer.py

socket.error: [Errno 48] Address already in use

I get this error after every time I stop (ctrl + z) and restart (python SimpleExampleServer.py). I have to use a new port for every run. Am I doing something wrong? Is the socket not being removed correctly?

I have checked that Python is not still running in the force quit applications window.

how to run example

When running python SimpleExampleServer.py --example echo I am not able to see received responses via:

socat - TCP:localhost:8000

There is simply no output after trying to connect to the websocket. How should this example websocket server be communicated with?

I know I am able to setup a websocket server because other tools work, such as wscat:

sudo npm install -g wscat
wscat -l 8000 -p 13
listening on port 8000 (press CTRL+C to quit)
client connected
< {"text":"hello"}

Also, In order to run the example after installing using pip, i must first cd:

cd /Library/Python/2.7/site-packages/SimpleWebSocketServer

otherwise I get:

python SimpleExampleServer.py --example echo
python: can't open file 'SimpleExampleServer.py': [Errno 2] No such file or directory

Should the docs be updated to include cd'ing to that directory first?

Is there any example that the server push directly to the clients?

In the examples, I found all the sendMessage calls were triggered by handleMessage or handleConnected.
I want to call sendMessage at any time I want. Such as everytime I read a line from stdin.

So I wrote such script, however it didn't work.

#!/usr/bin/env python

import threading
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

conns = []

class SimpleStdinPub(WebSocket):

    def handleConnected(self):
        conns.append(self)

    def handleClose(self):
        conns.remove(self)


server = SimpleWebSocketServer('0.0.0.0', 9000, SimpleStdinPub)


def read_stdin():
    while True:
        line = raw_input()
        for conn in conns:
            conn.sendMessage(line)

if __name__ == '__main__':
    t = threading.Thread(target=server.serveforever)
    t.setDaemon(True)
    t.start()
    read_stdin()

I tried all kinds of ways. It seems it doesn't work when I call sendMessage in another thread.
But I can't figure out any way I can call sendMessage in the same thread.

Could anyone tell me how could I achieve this?
Thanks :)

ValueError: filedescriptor out of range in select()

This is the second time I'm getting the exception ValueError: filedescriptor out of range in select().

The server is running inside a Docker container under Alpine Linux 3.4. It has been running for six weeks without a restart with about three continuous connections during the entire time that were publishing data during the entire time, about 1x100byte message per 5 seconds. Not much disconnect/reconnect going on except for about 5 subscribers a day for a period of about one minute each.

Traceback (most recent call last):
  File "websocket.py", line 62, in <module>
    server.serveforever()
  File "/usr/lib/python2.7/site-packages/SimpleWebSocketServer/SimpleWebSocketServer.py", line 609, in serveforever
    rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval)
ValueError: filedescriptor out of range in select()

Is this an OS thing or could it be related to the server?

Send message from server

What would be the correct way of sending a message from the server (say a notification) to a connected client? The following doesn't seems to work:

class ParallelWebsockets(SimpleWebSocketServer):

    def __init__(self, HOST, WSOCK_PORT, RequestHandlerClass):
        SimpleWebSocketServer.__init__(self, HOST, WSOCK_PORT, RequestHandlerClass)
        self.clients = []

    def serverMessage(self):
        print 'sending server message'
        #print self.clients
        for client in self.clients:
            client.sendMessage('server says Hi')

WebsockInstance = ParallelWebsockets(HOST, WSOCK_PORT, WebsocketHandler)
WebsockInstance.serverMessage()

much obliged

can't install properly with Python3

Having installed with pip3 using either of "setup.py" and "git+https" methods, can't execute example server.
First error is "cannot import name 'WebSocket'".
If import from the SimpleWebSocketServer dir directly, works fine.
Pip for py2 works normally.

intermittent hang when sending

I've been trying to track this problem down for 5 days, and I ## think ## I may finally know the cause.

I am broadcasting to all connected clients once a second, once in a while (maybe once or twice a day) the server will stop responding to the connected clients, it looks like the call to sendMessage() is never returned, and instead of returning to the loop, an exception is raised due to a socket error which then fires the handleClose() event.

I think that this means that my loop is stuck waiting for the return from sendMessage() which never happens.

The problem is, this is difficult to pinpoint as it happens intermittently and not frequently, but it does result in the server entering a frozen state, here's the snippets of code:

for client in self.server.connections.values():
  try:
    client.sendMessage(ODATA)
  except Exception as n:
    print "Send Failed"

The sendBuffer() throws an exception, which means that the sendMessage() is never returned:

def sendBuffer(self, buff):
    .....
    except socket.error as e:
        # if we have full buffers then wait for them to drain and try again
        if e.errno == errno.EAGAIN:
            time.sleep(0.001)
        else:
            raise e

I suspect that something similar may also happen during a bad receive.

Ping/Pong with TTL

Currently the library just receives pings and pings, but discards them. Sending a ping is only available by using _sendMessage(False, 0x9) which is discouraged. A proper handling like "send ping, if no response after x seconds and y tries, close connection".
If I have enough time, I may open a PR.

select.error: (4, 'Interrupted system call')

Hi

I want to use websocket for Automatic Speech Recognition (ASR) server side. I try to load models in __init__. After the models loaded successfully,the following exception thrown out:

Selected GPU[0] GeForce GTX 1060 6GB as the process wide default device.
ASR model loaded successfully
(('127.0.01', 56236), 'connected')
Traceback (most recent call last):
File "websocket_server2.py", line 111, in
server.serveforever()
File "/home/aj/anaconda3/envs/cntk-py27/lib/python2.7/site-packages/SimpleWebSocketServer/SimpleWebSocketServer.py", line 677, in serveforever
self.serveonce()
File "/home/aj/anaconda3/envs/cntk-py27/lib/python2.7/site-packages/SimpleWebSocketServer/SimpleWebSocketServer.py", line 618, in serveonce
rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval)
select.error: (4, 'Interrupted system call')

My class defined as bellow:

# -*- coding: utf-8 -*-
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
from ASR import ASR


class SimpleEcho(WebSocket):

    def __init__(self, server, sock, address):
        super(SimpleEcho, self).__init__(server, sock, address)
        self.asr = ASR()

    def handleMessage(self):
        data = np.frombuffer(self.data, 'i2')
        result = self.asr(data)
        self.sendMessage(unicode(result))

    def handleConnected(self):
        print(self.address, 'connected')
        self.sendMessage(unicode('connection stablished...'))

    def handleClose(self):
        print(self.address, 'connection closed')
        self.sendMessage(unicode('connection closed...'))

server = SimpleWebSocketServer('0.0.0.0', 8081, SimpleEcho)
server.serveforever()

What cause such exception and how can I avoid it?
regards.

License in source + python module file

Thanks for licensing this script under MIT! Forgot to thank you earlier.

One small request however. We'd like to use this module for an internal project at my company but in order to comply with the open source policies we require the license to be present at the top of each source file (I think the MIT license specifies this in its terms).

Also, could you please add a blank __init__.py to this repository too, so the folder can act as a python module and we can import it nicely?

Many thanks!

Occasional "bad file descriptor" crash

I got the following crash:

Traceback (most recent call last): File "chat.py", line 662, in server.serveforever() File "/path/SimpleWebSocketServer/SimpleWebSocketServer.py", line 607, in serveforever super(SimpleSSLWebSocketServer, self).serveforever() File "/path/SimpleWebSocketServer/SimpleWebSocketServer.py", line 541, in serveforever fileno = client.client.fileno() File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) File "/usr/lib/python2.7/socket.py", line 170, in _dummy raise error(EBADF, 'Bad file descriptor')

I'm not really sure what caused it.

Multiple sockets problem

Hi,
I have a SocketWebServer to comunicate to web client, a and a have a separate socket opened in another thread for reading incoming requests from different clients.

WebServer is set to 5000 and the second socket si set to 8484. When I call server.serveforver() the second socket stops receving data. Here is the code:

HOST = '10.32.78.1'
UDP_PORT = 8484
WEB_SERVER_PORT = 5000
SOCKET_TIMEOUT = 4

class GenericThread(Thread):
    def __init__(self, start=True):
        Thread.__init__(self)
        self.running = False
        if start:
            self.start()

    def start(self):
        if not self.running:
            self.running = True
            super(GenericThread, self).start()

    def run(self):
        while self.running:
            self.loop()

    def stop(self):
        if self.running:
            self.running = False
            self.join()

    def loop(self):
        raise NotImplementedError


class SocketComunicationWorker(GenericThread):
    """ receives all the traffic """
    def __init__(self, socket):
        self.socket = socket
        super(SocketComunicationWorker, self).__init__()

    def loop(self):
        try:
            raw_response, (incoming_ip, port) = self.socket.recvfrom(1024)
            """ process the response """
            # cs.handle_socket_response(raw_response, incoming_ip, self.socket)
        except socket.timeout:
            pass

sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sckt.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sckt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sckt.settimeout(SOCKET_TIMEOUT)
sckt.bind((HOST, UDP_PORT))

socket_thread = SocketComunicationWorker(sckt)

srvr = RigWebserver(HOST, WEB_SERVER_PORT, WebSocket)
srvr.serveforever()

So, socket_thread is not receiving data after a to call to serveforever. Is this normal behaviour?

error code when closing the socket because of an error

Hi, I have a simple echo example with a counter for total number of messages the server has received:

from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

count = 0
class SimpleEcho(WebSocket):

    def handleMessage(self):
        # echo message back to client
        print 'received ', self.data, ' from ', self.address
        #count = count+1
        msg = self.data[::-1] + str(count)
        self.sendMessage(msg)
        count = count + 1

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

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

server = SimpleWebSocketServer('', 8080, SimpleEcho)
server.serveforever()

then I have a simple javascript connection:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Sample of websocket with python</title>
        <script src="jquery-2.1.4.min.js"></script>
        <script>
      $(function() {
        var ws = new WebSocket("ws://localhost:8080");
        ws.onmessage = function(e) {
          $('<li>').text("received: " + e.data).appendTo($ul);
        };

        var $ul = $('#msg-list');
        $('#sendBtn').click(function(){
          var data = $('#name').val();
          ws.send(data);
          $('<li>').text("send: " + data).appendTo($ul);
        });
      });
        </script>
    </head>
    <body>
            <input id="name" type="text" />
            <input type="button" id="sendBtn" value="send"></input>
      <ul id="msg-list"></ul>
    </body>
</html>

this fails by closing the socket:

$ python main.py
('127.0.0.1', 59238) connected
received  sfdfsdf  from  ('127.0.0.1', 59238)
('127.0.0.1', 59238) closed

it works fine if I don't change the value of count in the socket class, but I want to understand where is the problem and tried to print a lot of different fields of the ws object in the handleClose method but I can't find any error or debugging message.

Release on PYPI

As things stand, one cannot use this as a dependency in a python library (installed by pip) and have this installable by other people. Basically pip has decided to deprecate git dependencies (pypa/pip#4187) and provided no work around.

The easy work around is to provide this on pypi. This adds a bunch of complexity / credential / moving parts.

ssl connection crashed on python 2.7

once click the connection with ssl enabled(wss), the example crash like

python SimpleExampleServer.py --example chat --ssl 1 --cert ./cert.pem
Traceback (most recent call last):
File "SimpleExampleServer.py", line 71, in
server.serveforever()
File "/root/kw/wss/SimpleWebSocketServer.py", line 696, in serveforever
super(SimpleSSLWebSocketServer, self).serveforever()
File "/root/kw/wss/SimpleWebSocketServer.py", line 654, in serveforever
client.handleClose()
File "SimpleExampleServer.py", line 38, in handleClose
clients.remove(self)
ValueError: list.remove(x): x not in list

Overzealous exception handling during handshake

When an exception occurs inside handleConnected, it's re-raised inside _handleData and then caught again inside the main serveForever loop.

The connection is then silently closed (no traceback is shown) so this can make it tricky to find the culprit of a misbehaved websocket. My sense would be to replace instances of raise Exception("Some websocketty thing") with raise WebSocketException("Some websocketty thing") so that they can be explicitly caught in the top-level select loop, and implementors of the WebSocket class will find their code crashing early and often ๐Ÿ˜ฌ

I'd send a pull request, but I'm not sure I fully grok all the avenues of control flow wherein it would be advantageous to do something different, nor am I equipped to test it ๐Ÿ˜•

Messages grouped into 100ms intervals

I'm using this to send image frame data of variable size at framerates up to 60fps. However, I've noticed in the packet timings, both in Chrome and Wireshark, that everything comes in as groupings about every 100ms. For example, if pushing packets at 30 per second, I usual will get timing such as: 102, 103, 103, 203, 204, 205, 302, 302, 303 where each of those numbers are the milliseconds portion of the timestamp shown in Chrome or Wireshark. If I run at 60fps then I will get around 5-6 packets grouped together.

I've added debug outputs in my WebSocket class when sending and it does not show the sends happening this way, as the timestamps are all nicely spread apart.

I thought at first that maybe it was simply on the receiving end as shown by the network timings in Chrome, but Wireshark seems to prove this incorrect. In Wireshark I can see the groupings which suggest that although sendMessage() happens in a timely manner that the actual packets don't make it to the network right as they are sent. Note: this is all happening on localhost.

Also, this is occurring on Windows 10 and Fedora 24 in Chrome 56.

Any thoughts on what might be the cause of this?

Client Disconnect Errors & Client Connection State

I am getting errors if a client disconnects and the server tries to send a message to the closed connection.

Although I am trapping it, it still results in continued "[Errno 9] Bad file descriptor" errors.

How can I tell the connected state of the client, I have tried looking at the self.client object, but I cannot see anything obvious there that will show the connection state.

I would like to check that the connection is alive before trying to send a message, as these messages are broadcasted automatically every second, and sometimes a client disconnects.

Intermittent frame corruption

I use this package in conjunction with websocket-client (https://pypi.python.org/pypi/websocket-client/) for the application. While running regressions on this application, intermittently, the client raises a WebSocketPayLoadException and on a closer look, it appears that the server is sending binary data in a text frame (possibly the control frame spills over into data frame?)

data = ws.recv()
File "/usr/local/lib/python2.7/site-packages/websocket_client-0.21.0-py2.7.egg/websocket/_core.py", line 667, in recv
opcode, data = self.recv_data()
File "/usr/local/lib/python2.7/site-packages/websocket_client-0.21.0-py2.7.egg/websocket/_core.py", line 684, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/usr/local/lib/python2.7/site-packages/websocket_client-0.21.0-py2.7.egg/websocket/_core.py", line 724, in recv_data_frame
raise WebSocketPayloadException("cannot decode: " + repr(frame.data))
websocket._exceptions.WebSocketPayloadException: cannot decode: '\x81~\x01?'

I'm certain that the application doesn't inject any data since we use the same backend via a different channel.

Server swallows exceptions

I appreciate the easy of use of this library, so thanks for that!

What I don't appreciate is that it silently eats exceptions that occur in any method of a child class of WebSocket.

I tried to add logging, as suggested in #31, but there are too many except: pass everywhere and I don't know which are just catching KeyErrors and which should have logging.

Occasionally hangs in ssl do_handshake()

I've been experiencing a lot of "hangs" recently, where the server simply stops responding to anything. I set my code to dump the stack on SIGINT I get the following:

File: "chat.py", line 856, in <module>
  server.serveforever()
File: "SimpleWebSocketServer/SimpleWebSocketServer.py", line 609, in serveforever
  super(SimpleSSLWebSocketServer, self).serveforever()
File: "SimpleWebSocketServer/SimpleWebSocketServer.py", line 530, in serveforever
  newsock = self.decorateSocket(sock)
File: "SimpleWebSocketServer/SimpleWebSocketServer.py", line 600, in decorateSocket
  ssl_version=self.version)
File: "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
  ciphers=ciphers)
File: "/usr/lib/python2.7/ssl.py", line 143, in __init__
  self.do_handshake()
File: "/usr/lib/python2.7/ssl.py", line 305, in do_handshake
  self._sslobj.do_handshake()
File: "chat.py", line 845, in close_sig_handler
  for filename, lineno, name, line in traceback.extract_stack(stack):

Looking around Google, it seems that a number of people (particularly on Debian and using OpenSSL, which is my setup) are experiencing occasional hangs in ssl.py's do_handshake() so this isn't really a SimpleWebSocketServer issue. However, the only solution I've found so far is to modify SimpleWebSocketServer.py to set a timeout on the decorateSocket() call, using something akin to what is suggested here: http://stackoverflow.com/a/2282656/146587

Unable to connect to ws server

I am fairly new to programming and python. I did as explained in the homepage.

  1. Installed using the command sudo pip install git+https://github.com/dpallot/simple-websocket-server.git
  2. Downloaded the files init.py ,SimpleHTTPSServer.py,websocket.html, SimpleExampleServer.py, SimpleWebSocketServer.py
  3. Right click and opened websocket.html with chrome.

When I try to press the connect button, I get error

error: undefined
disconnected

What could be the possible issue? I did some mistakes in the procedures?

handleClose triggered on client connect

Using the SSL SimpleChat class, I get a handleClose event on every client connect. So it of course errors with: ValueError: list.remove(x): x not in list this error was mentioned in the issue listed by vusdo.

An easy work around is:
def handleClose(self): if self in clients: clients.remove(self)
but it still shouldn't be running handleClose when a client connects. I have confirmed the connection is NOT being closed from the client (javascript).

bad file descriptor when using __init__()

I need to use an init function to initialize some variables and call a threaded function inside the simpleEcho class:

class SimpleEcho(WebSocket):

    def myfunc():
        do something...

    def __init__(self):
        self.varx = 1
        self.myfunc()

    def handleMessage(self):
       if self.data is None:
          self.data = ''........

But whenever I add the init the server fails with an "bad file descriptor error"

Traceback (most recent call last):
  File "websock.py", line 75, in <module>
    server.serveforever()
  File "SimpleWebSocketServer.py", line 534, in serveforever
    rList, wList, xList = select(self.listeners, [], self.listeners, 1) 
select.error: (9, 'Bad file descriptor')

I am using your code!

Good morning Dave,

I created a simple POC two years ago based on your code.
(https://github.com/dpallot/simple-websocket-server/blob/e57f4c8112d49bad8301ba326385a8a8cd21b1a2/SimpleWebSocketServer.py).

It seems to become (a little) more popular and people seems to care about licensing.
First of all Thanks you for this piece of code and making it Open Source.

Then ... I just wanted to tell you that I am using your code and I am considering Open Sourcing mine too. You can find the project here : https://github.com/Paraintom/FastFlicker

Have a nice day!
Thomas

Integration with web.py

Hello I'm writing simple app with web.py, and I'd like to integrate it with your lib.
However I have problem with combining it together.
Because serveforever() method runswhile True loop, I cannot run webpy's app.run() method, which is needed to start the server. Without app.run() I cannot open connection from browser (my index page is not static - it is rendered by web py), so serveforever is still waiting.
If I change the order and first I call app.run(), then I cannot call serveforever().

Do you have any idea how to solve this problem?
I've tried to do something with threads but I cannot share "sendMessage" method between them.

Code draft http://pastebin.com/Hbq4DiEy

Run Web Socket in a separate thread

Hi, I'm trying to run Web Socket server in another thread while being able to send messages to clients:

clients = []
class SimpleChat(WebSocket):

    def handleMessage(self):
       for client in clients:
          if client != self:
             client.sendMessage(self.address[0] + ' - ' + self.data)

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

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

def run_server():
    server = SimpleWebSocketServer.SimpleWebSocketServer('', 9000, SimpleChat)
    server.serveforever()

t = threading.Thread(target=run_server)
t.start()

while True:
    for client in clients:
        client.sendMessage('ping')
    time.sleep(1)

It doesn't seem to be sending any messages. Is it because the loop is blocking the main thread? Is there any better way to do it?

Class not binding on ubuntu 14.04.1 LTS

On ubuntu 14.04 the code binds to the port indicated but it seems the class is not bound (no connected messages, no echo's)
i tried python 2.7.6, 2.7.11 and python3

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.