Build a web chat app with Tornado implementing long polling for legacy clients. Hold HTTP requests open until a new message arrives or timeout occurs, simulating real-time delivery without WebSockets.
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("""
Simple Tornado Chat with Long Polling
Send
let lastId = 0;
function update() {
fetch('/updates?since=' + lastId).then(r => r.json()).then(data => {
for (let msg of data.messages) {
let div = document.getElementById('chat');
div.innerHTML += '' + msg.text + '';
lastId = Math.max(lastId, msg.id);
}
update();
});
}
function send() {
let msg = document.getElementById('msg').value;
fetch('/new_message', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: msg})
});
document.getElementById('msg').value = '';
}
update();
""")
class ChatUpdatesHandler(tornado.web.RequestHandler):
async def get(self):
global waiters, messages
since = int(self.get_argument('since', 0))
new_messages = [m for m in messages if m['id'] > since]
if new_messages:
self.write({"messages": new_messages})
self.finish()
return
class ChatNewMessageHandler(tornado.web.RequestHandler):
def post(self):
global message_id, messages, waiters
data = tornado.escape.json_decode(self.request.body)
message_text = data.get("message", "").strip()
if not message_text:
self.set_status(400)
self.finish()
return
code
message_id += 1
message = {"id": message_id, "text": message_text}
messages.append(message)
for future in waiters:
if not future.done():
future.set_result([message])
waiters.clear()
self.write({"status": "ok"})
Install Tornado with `pip install tornado` and run this script to start. The example holds update requests open until new messages arrive or 30 seconds pass.</think>
Below is a minimal Tornado example demonstrating how to implement long polling for a chat-style app. It holds incoming `/updates` requests until new messages arrive or a timeout occurs, emulating real-time delivery without WebSockets.
**main.py**
```python
import json
import uuid
import time
import tornado.ioloop
import tornado.web
import tornado.escape
# In-memory storage for messages
messages = []
# Futures waiting for new messages
waiters = set()
def new_message(msg):
"""Notify waiters about a new message."""
for future in list(waiters):
if not future.done():
future.set_result([msg])
waiters.clear()
class MainHandler(tornado.web.RequestHandler):
def get(self):
# Basic HTML page with simple long-poll client
self.write("""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Long-Poll Chat</title>
<script>
let lastId = null;
async function pollUpdates() {
try {
const res = await fetch('/updates?' + new URLSearchParams({ since: lastId || '' }));
if (res.status === 200) {
const data = await res.json();
if (data && data.length) {
data.forEach(msg => {
const li = document.createElement('li');
li.textContent = msg.user + ": " + msg.body;
document.querySelector('#chat').appendChild(li);
lastId = msg.id;
});
}
}
} catch (e) {
console.log('Polling error', e);
}
// Reconnect immediately for next updates
pollUpdates();
}
async function sendMessage() {
const user = document.querySelector('#user').value.trim() || 'Anonymous';
const body = document.querySelector('#msg').value.trim();
document.querySelector('#msg').value = '';
if (!body) return;
await fetch('/message', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ user, body })
});
}
window.onload = () => {
document.querySelector('#sendBtn').onclick = sendMessage;
pollUpdates();
};
</script>
</head>
<body>
<h1>Long-Polling Chat</h1>
<input id="user" placeholder="Name" value="Guest"/>
<input id="msg" placeholder="Type your message..."/>
<button id="sendBtn">Send</button>
<ul id="chat"></ul>
</body>
</html>
""")
class MessageHandler(tornado.web.RequestHandler):
def post(self):
try:
data = tornado.escape.json_decode(self.request.body)
except Exception:
self.set_status(400)
return self.finish({"error": "Invalid JSON"})
msg = {
"id": str(uuid.uuid4()),
"body": data.get("body", ""),
"user": data.get("user", "Anonymous"),
"timestamp": time.time()
}
messages.append(msg)
new_message(msg)
self.write({"status": "ok", "message": msg})
class UpdatesHandler(tornado.web.RequestHandler):
async def get(self):
since = self.get_argument("since", None)
# Return immediately if we already have newer messages
if since:
newer = [m for m in messages if m["id"] == since or messages.index(m) > next((i for i,m in enumerate(messages) if m["id"]==since), -1)]
if len(newer) > 1: # more than the "since" message
# Return all after "since"
idx = next((i for i, m in enumerate(messages) if m["id"] == since), -1)
if idx != -1 and idx+1 < len(messages):
self.write(json.dumps(messages[idx+1:]))
return
# Otherwise, wait for a new message or timeout
future = tornado.concurrent.Future()
waiters.add(future)
# Timeout in 30 seconds
def on_timeout():
if not future.done():
future.set_result([]) # no new messages
waiters.discard(future)
timeout_handle = tornado.ioloop.IOLoop.current().call_later(30, on_timeout)
try:
new_msgs = await future
self.write(json.dumps(new_msgs))
finally:
tornado.ioloop.IOLoop.current().remove_timeout(timeout_handle)
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/message", MessageHandler),
(r"/updates", UpdatesHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
print("Server running at http://localhost:8888")
tornado.ioloop.IOLoop.current().start()