Connection closes immediately on open
<p>I am running a very simple echo websocket server as below:</p>

<pre><code>#!/usr/bin/python

import datetime
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web



class WSHandler(tornado.websocket.WebSocketHandler):
    clients = []
    def open(self):
        print('new connection')
        self.write_message("Hello World")
        WSHandler.clients.append(self)

    def on_message(self, message):
        print('message received %s' % message)
        self.write_message('ECHO: ' + message)

    def on_close(self):
        print('connection closed')
        WSHandler.clients.remove(self)

    @classmethod
    def write_to_clients(cls):
        print("Writing to clients")
        for client in cls.clients:
            client.write_message("Hi there!")

    def check_origin(self, origin):
        return True



application = tornado.web.Application([
  (r'/websocket', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(80)
    tornado.ioloop.IOLoop.instance().start()
</code></pre>

<p>I am connecting to this with javascript as below</p>

<pre><code>var ws = new WebSocket("ws://localhost:80/websocket");
</code></pre>

<p>In the console I see </p>

<pre><code>new connection
connection closed
</code></pre>

<p>What I do not understand is why I am seeing the <code>connection closed</code> in the console. The client also indicates that the connection is closed but I do not see any good reason for this. Any help would be greatly appreciated. To replicate run the python code as admin, open any JS console and enter the JS code. My desired outcome is for the socket to not be immediately closed. This is somewhat based on what I read in the <a href="http://www.tornadoweb.org/en/stable/websocket.html" rel="nofollow">tornado docs</a>. </p>

<hr>

<p><strong>edit</strong> update by commenting out <code>self.write_message("Hello World")</code> in the <code>open</code> method, the connection does not close. However running the example code from the docs now yields something interesting.</p>

<pre><code>var ws = new WebSocket("ws://localhost:80/websocket");
ws.onopen = function() {
   ws.send("Hello, world");
};
ws.onmessage = function (evt) {
   alert(evt.data);
};
</code></pre>

<p>server side output is</p>

<pre><code>new connection
message received Hello, world
connection closed
</code></pre>

<p>There is no corresponding alert on the client side as expected</p>

<p>The new question is the same as the old which is why does the server say <code>connection closed</code>? It looks like <code>self.write_message</code> may be the culprit. </p>