gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
html css js chat server no socket
- User
html css js chat server no socket
- Assistant
html css js chat server no socket
Creating a real-time chat application without sockets is challenging since WebSockets or similar mechanisms (like Server-Sent Events) are the standard for real-time duplex communication.
However, if you want to build a very simple chat server system without sockets, you can approximate real-time communication by polling the server periodically using HTTP requests (AJAX). This approach is less efficient and real-time but can work for lightweight or demo purposes.
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());
let messages = [];
app.get('/messages', (req, res) => {
res.json(messages);
});
app.post('/messages', (req, res) => {
const { user, text } = req.body;
if(typeof user === 'string' && typeof text === 'string') {
const message = { user, text, timestamp: new Date().toISOString() };
messages.push(message);
res.status(201).json(message);
} else {
res.status(400).json({ error: 'Invalid message format' });
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Chat server running on http://localhost:${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple Polling Chat</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: auto; }
#messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
#input-area { margin-top: 10px; }
#status { font-size: 0.9em; color: gray; }
</style>
</head>
<body>
<h2>Simple Polling Chat</h2>
<div id="messages"></div>
<div id="input-area">
<input id="user" placeholder="Your name" />
<input id="text" placeholder="Your message" />
<button id="send">Send</button>
</div>
<div id="status"></div>
<script>
const messagesDiv = document.getElementById('messages');
const userInput = document.getElementById('user');
const textInput = document.getElementById('text');
const sendButton = document.getElementById('send');
const statusDiv = document.getElementById('status');
const API_URL = 'http://localhost:3000/messages';
// Load and display messages
async function loadMessages() {
try {
const response = await fetch(API_URL);
const data = await response.json();
messagesDiv.innerHTML = '';
data.forEach(msg => {
const msgElem = document.createElement('div');
const time = new Date(msg.timestamp).toLocaleTimeString();
msgElem.textContent = `[${time}] ${msg.user}: ${msg.text}`;
messagesDiv.appendChild(msgElem);
});
messagesDiv.scrollTop = messagesDiv.scrollHeight;
statusDiv.textContent = "Connected";
} catch(e) {
statusDiv.textContent = "Cannot connect to server";
}
}
// Send a new message
async function sendMessage() {
const user = userInput.value.trim();
const text = textInput.value.trim();
if(!user || !text) return alert('Enter name and message');
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ user, text })
});
if(response.ok) {
textInput.value = '';
loadMessages(); // Refresh after send
} else {
alert('Failed to send message');
}
} catch(e) {
alert('Error sending message');
}
}
sendButton.addEventListener('click', sendMessage);
textInput.addEventListener('keypress', e => {
if(e.key === 'Enter') sendMessage();
});
// Poll for new messages every 3 seconds
setInterval(loadMessages, 3000);
loadMessages();
</script>
</body>
</html>
chat-server.js.npm init -y, then npm install express cors body-parser.node chat-server.js.index.html in your browser (you can open it from file or serve it with a static server).If you want truly real-time, consider using WebSocket libraries like socket.io or Server-Sent Events.
Let me know if you need an example with those or want to improve this further!
Not yet included in a published release.