2

I am attempting to run a Python WebSocket server with AutoBahn[twisted].

Here is the code in my server (Python):

*various imports*

class webSocket(WebSocketServerProtocol):
def onConnect(self, request):
    print("some request connected {}".format(request))

def onMessage(self, payload, isBinary):
    self.sendMessage("message received")

log.startLogging(sys.stdout)
root = File(".")

factory = WebSocketServerFactory(u"ws://0.0.0.0:8080")
factory.protocol = webSocket

resource = WebSocketResource(factory)

root.putChild(u"ws", resource)

site = Site(root)
reactor.listenTCP(8080, site)
reactor.run()

Here is the code in my client (Javascript):

window.webSocket = new WebSocket("ws://localhost:8080");
      webSocket.onclose=function(event){
        console.log(event)
        setTimeout(connectToSocket, 1000);
      }

However, the Javascript will just keep throwing the following error (and trying to reconnect):

WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
acfluff
  • 25
  • 3
  • I have the same problem and still didn't get an answer. Also on try to connect server prints IP,datetime and browser verseion client trying to connect. But print('test') don't appears in place onConnect and onMessage. – scrache Jan 22 '19 at 18:20
  • Looks like onConnect doesn't execute so can't execute my own handshake code – scrache Jan 22 '19 at 18:28

1 Answers1

0

You mounted the WebSocketResource at /ws. Try changing your client to reflect this:

window.webSocket = new WebSocket("ws://localhost:8080/ws");
...
Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122