Skip to content
Advertisement

Tornado gives error Cannot write() after finish()

I am using the Tornado chat demo example from here: https://github.com/tornadoweb/tornado/tree/master/demos/chat and just altering it very slightly. The code change is just a small class called Connections and a bit in the MessageNewHandler(). All I am doing is just saving a reference to self and trying to write(message) to a previous client.

But when I go to save on this line conns.conns[0].write(message) I get this error message:

JavaScript

[E 220107 23:18:38 web:2239] 500 POST /a/message/new (::1) 5.98ms

Here is the code:

JavaScript

Advertisement

Answer

You’re writing to an already closed connection, that’s why you’re seeing the error.

If you want to write to a previously connected client, you’ve keep that connection open.

However, this – conns.add_connection(self) – doesn’t make sense to track regular http connections.

You should consider using websockets if you want to keep previous connections open and track them.


Update: Here’s how you can keep a connection open. If I understand correctly, you want to send a message from current client to the previous client.

1. Using tornado.locks.Condition():

JavaScript

2. Using tornado.concurrent.Future():

JavaScript

3: A more practical example using tornado.concurrent.Future():

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement