Creating a real-time chat server without using WebSockets or Node.js is quite challenging because these technologies are the standard tools for full-duplex communication between client and server. However, you can still build a basic chat-like application using long polling or frequent polling with just HTML, CSS, JavaScript, and a server that supports HTTP requests (like PHP, Python Flask, etc).
Below is a very simple example using long polling with:
- HTML/CSS/JS for the front end
- A simple backend simulated via comments (you can implement in any server language)
How it works:
- Clients send messages via
POST.
- Clients ask for new messages by
GET with long polling (the server holds the request until new messages arrive or timeout occurs).
- No WebSocket or Node.js is used.
Frontend (HTML + CSS + JS)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Long Polling Chat</title>
<style>
body { font-family: Arial, sans-serif; margin: 2em; max-width: 600px; }
#chat { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; margin-bottom: 10px;}
#chat p { margin: 5px 0; }
#message { width: 80%; }
#send { width: 18%; }
</style>
</head>
<body>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type a message..." autocomplete="off" />
<button id="send">Send</button>
<script>
const chatDiv = document.getElementById('chat');
const messageInput = document.getElementById('message');
const sendBtn = document.getElementById('send');
let lastMessageId = 0;
// Append messages to chat window
function appendMessage(text) {
const p = document.createElement('p');
p.textContent = text;
chatDiv.appendChild(p);
chatDiv.scrollTop = chatDiv.scrollHeight;
}
// Send a message to the server
function sendMessage() {
const text = messageInput.value.trim();
if(!text) return;
fetch('/send-message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
}).then(res => res.json())
.then(data => {
if(data.success) {
messageInput.value = '';
} else {
alert('Failed to send message');
}
}).catch(() => alert('Server error sending message'));
}
// Poll for new messages using long polling
function pollMessages() {
fetch('/get-messages?lastId=' + lastMessageId)
.then(res => res.json())
.then(data => {
if(data.messages && data.messages.length) {
data.messages.forEach(msg => {
appendMessage(msg.text);
lastMessageId = msg.id;
});
}
pollMessages(); // Continue polling immediately after response
})
.catch(err => {
console.error('Polling error', err);
// Retry after delay on error
setTimeout(pollMessages, 3000);
});
}
sendBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keydown', e => {
if(e.key === 'Enter') sendMessage();
});
pollMessages(); // start polling on load
</script>
</body>
</html>
Backend Explanation (Pseudocode)
Since you want no Node.js and no sockets, your backend can be implemented in any language (PHP, Python Flask, Ruby, etc.). Here's what the backend needs to do:
-
Store messages in memory or persistent storage, each with incremental unique ID.
-
POST /send-message endpoint:
- Accept JSON
{ text: "..." }
- Add the message to the store with a unique incremental ID and timestamp
- Return JSON
{ success: true }
-
GET /get-messages?lastId=NUMBER endpoint (long polling):
- Check if there are messages with
id > lastId
- If yes, immediately return JSON
{ messages: [ ... ] }
- If no, hold the request open (e.g., for max 30 seconds), waiting for new messages
- If during this time a new message arrives, return it immediately
- Otherwise return empty
{ messages: [] } and client polls again
Example PHP backend
Here is a simple example using PHP with session storage (for demonstration only, not production ready):
<?php
session_start();
if (!isset($_SESSION['messages'])) {
$_SESSION['messages'] = [];
$_SESSION['last_id'] = 0;
}
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/send-message') {
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['text']) && trim($data['text']) !== '') {
$_SESSION['last_id'] += 1;
$_SESSION['messages'][] = ['id' => $_SESSION['last_id'], 'text' => htmlspecialchars($data['text'])];
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false]);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && strpos($_SERVER['REQUEST_URI'], '/get-messages') === 0) {
$lastId = intval($_GET['lastId'] ?? 0);
// Long poll timeout
$timeout = 30;
$start = time();
while (true) {
$messages = array_filter($_SESSION['messages'], fn($m) => $m['id'] > $lastId);
if (count($messages) > 0) {
echo json_encode(['messages' => array_values($messages)]);
break;
}
if ((time() - $start) >= $timeout) {
echo json_encode(['messages' => []]);
break;
}
usleep(100000); // 100ms
session_write_close(); // important to allow other requests
session_start();
}
exit;
}
// If none matches:
http_response_code(404);
echo json_encode(['error' => 'Not found']);
Summary
- The frontend uses polling with Fetch API to simulate real-time update.
- Backend holds HTTP GET requests and only responds on new messages or timeout.
- No WebSockets, no Node.js required.
- You can implement backend in any language that supports HTTP and sessions or persistent storage.
If you want a demo running on your machine, you can do the backend part in PHP above and serve it through Apache or built-in PHP server:
php -S localhost:8000
And open the HTML file in your browser (adjust fetch URLs accordingly).
If you want me to produce a backend in another language or run fully in client (like localStorage chat between multiple tabs), just ask!