Create WebSocket app
- User
Create WebSocket app
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Create WebSocket app
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's create a basic real-time chat application using WebSockets. This example will consist of:
ws library to handle WebSocket connections.This setup will allow multiple clients (browser tabs) to connect to the server, and when one client sends a message, it will be broadcast to all other connected clients in real-time.
Prerequisites:
Step 1: Set Up the Project
mkdir websocket-chat-app
cd websocket-chat-app
npm init -y
ws library:
npm install ws
public):
mkdir public
Step 2: Create the Server (server.js)
Create a file named server.js in the root of your project directory (websocket-chat-app/server.js) and add the following code:
// Import the WebSocket library and Node.js HTTP module
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const path = require('path');
// Define the port for the WebSocket server
const WS_PORT = 8080;
const HTTP_PORT = 3000; // Port for serving the HTML file
// Create a WebSocket server instance
const wss = new WebSocket.Server({ noServer: true }); // Use noServer: true because we'll handle HTTP requests ourselves
console.log(`WebSocket server starting on port ${WS_PORT}...`);
// --- WebSocket Event Handlers ---
// When a new client connects
wss.on('connection', (ws) => {
console.log('Client connected');
// Send a welcome message to the newly connected client
ws.send('Welcome! You are connected to the WebSocket server.');
// When a message is received from a client
ws.on('message', (message) => {
// Log the received message (convert Buffer to string)
const receivedMessage = message.toString();
console.log(`Received: ${receivedMessage}`);
// Broadcast the message to all *other* connected clients
wss.clients.forEach((client) => {
// Check if the client is connected and is not the sender
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(receivedMessage);
}
});
// Optional: Broadcast to everyone including the sender
// wss.broadcast(receivedMessage); // Use this if you want sender to see their own message reflected back
});
// When the client disconnects
ws.on('close', () => {
console.log('Client disconnected');
});
// Handle potential errors on the connection
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
// Helper function to broadcast messages to all clients (optional)
// wss.broadcast = function broadcast(data) {
// wss.clients.forEach(function each(client) {
// if (client.readyState === WebSocket.OPEN) {
// client.send(data);
// }
// });
// };
console.log(`WebSocket server is listening on port ${WS_PORT}`);
// --- HTTP Server to Serve Client Files ---
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code == 'ENOENT') {
// File not found
res.writeHead(404);
res.end('404 Not Found');
} else {
// Server error
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
// Success
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// --- Handle WebSocket Upgrade Requests ---
// This is crucial: We need to tell the HTTP server to handle WebSocket upgrades.
server.on('upgrade', (request, socket, head) => {
// Check if the request path is intended for the WebSocket server
if (request.url.startsWith('/ws')) { // You can define a specific path for WS if needed
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} else {
// Handle regular HTTP requests (handled by the http.createServer callback)
// This else block might not strictly be necessary if the http callback handles everything,
// but it clarifies the separation.
// The http.createServer handler below will manage non-upgrade requests.
// socket.destroy(); // Or pass it to the HTTP server logic if it hasn't already been handled
}
});
// Start the HTTP server
server.listen(HTTP_PORT, () => {
console.log(`HTTP server listening on port ${HTTP_PORT}`);
console.log(`Access the chat client at http://localhost:${HTTP_PORT}`);
});
// Simple broadcast function integrated into wss
wss.broadcast = function broadcast(data, senderWs = null) {
wss.clients.forEach(function each(client) {
// Check if the client is open and, if senderWs is provided, ensure it's not the sender
if (client.readyState === WebSocket.OPEN && client !== senderWs) {
client.send(data);
}
});
};
// Modify the message handler to use the broadcast function
wss.on('connection', (ws) => {
console.log('Client connected');
ws.send('Welcome! You are connected.');
ws.on('message', (message) => {
const receivedMessage = message.toString();
console.log(`Received: ${receivedMessage}`);
// Broadcast to all other clients
wss.broadcast(receivedMessage, ws);
});
ws.on('close', () => {
console.log('Client disconnected');
// Optionally notify others that a user left
wss.broadcast(`User has left.`, ws);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
// Announce that a new user joined
wss.broadcast(`A new user joined.`, ws);
});
Step 3: Create the Client (public/index.html)
Create a file named index.html inside the public directory (websocket-chat-app/public/index.html) and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat</title>
<style>
body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; }
#chatbox { height: 300px; border: 1px solid #ccc; margin-bottom: 10px; padding: 10px; background-color: #fff; overflow-y: scroll; }
#messageInput { width: calc(100% - 70px); padding: 10px; border: 1px solid #ccc; }
#sendButton { padding: 10px 15px; margin-left: 5px; background-color: #007bff; color: white; border: none; cursor: pointer; }
#sendButton:hover { background-color: #0056b3; }
.message { margin-bottom: 5px; }
.server-message { font-style: italic; color: gray; }
.user-message { font-weight: bold; color: green; }
</style>
</head>
<body>
<h1>Simple WebSocket Chat</h1>
<div id="chatbox">
<p class="message server-message">Connecting...</p>
</div>
<div>
<input type="text" id="messageInput" placeholder="Type your message...">
<button id="sendButton">Send</button>
</div>
<script>
const chatbox = document.getElementById('chatbox');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
// Construct the WebSocket URL based on the current page's protocol and host
const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
const wsHost = window.location.host; // Gets 'localhost:3000' or similar
const wsUrl = `${wsProtocol}${wsHost}/ws`; // Append /ws if needed by server logic
console.log(`Connecting to WebSocket: ${wsUrl}`);
const socket = new WebSocket(wsUrl);
// --- WebSocket Event Listeners ---
// Called when the connection is opened
socket.onopen = (event) => {
console.log('WebSocket connection established');
addMessage('Connected to server!', 'server-message');
messageInput.disabled = false;
sendButton.disabled = false;
};
// Called when a message is received from the server
socket.onmessage = (event) => {
console.log('Message from server:', event.data);
// Add the received message to the chatbox
addMessage(event.data, 'server-message'); // Assuming server messages are distinct
};
// Called when the connection is closed
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
addMessage('Disconnected from server.', 'server-message');
messageInput.disabled = true;
sendButton.disabled = true;
};
// Called when there's an error
socket.onerror = (error) => {
console.error('WebSocket error:', error);
addMessage('Connection error occurred.', 'server-message');
};
// --- Sending Messages ---
const sendMessage = () => {
const message = messageInput.value.trim();
if (message && socket.readyState === WebSocket.OPEN) {
// Send the message to the server
socket.send(message);
// Add the message to the chatbox (as if sent by the user)
addMessage(`You: ${message}`, 'user-message'); // Display as user message
// Clear the input field
messageInput.value = '';
} else if (socket.readyState !== WebSocket.OPEN) {
addMessage('Cannot send message: Not connected.', 'server-message');
}
};
// Send message when the button is clicked
sendButton.onclick = sendMessage;
// Send message when Enter key is pressed in the input field
messageInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
sendMessage();
}
});
// --- Helper function to add messages to the chatbox ---
function addMessage(msg, className = 'message') {
const p = document.createElement('p');
p.className = `message ${className}`;
p.textContent = msg;
chatbox.appendChild(p);
// Scroll to the bottom
chatbox.scrollTop = chatbox.scrollHeight;
}
// Initialize UI state
messageInput.disabled = true;
sendButton.disabled = true;
</script>
</body>
</html>
Step 4: Run the Application
websocket-chat-app/).node server.js
http://localhost:3000.Now, type a message in the input field on one browser tab and press Enter or click Send. You should see the message appear in both browser windows almost instantly! The server console will also log the received messages.
Explanation:
server.js:
index.html file.upgrade request from the browser. When a browser tries to establish a WebSocket connection (ws://...), the server.on('upgrade', ...) handler intercepts it./ws). If so, it passes the request to the wss.handleUpgrade method.wss (WebSocket Server) object listens for connection events.wss.on('connection', ...)), it gets a ws object representing that specific connection.ws for message, close, and error events.ws.on('message', ...)), it logs it and then iterates through wss.clients (all connected clients) to send the message to everyone except the original sender using the wss.broadcast helper.public/index.html:
WebSocket API (new WebSocket(...)).ws://localhost:3000/ws) tells the browser where the WebSocket server is listening. The protocol is ws:// (or wss:// for secure connections).onopen, onmessage, onclose, onerror) to handle the WebSocket lifecycle.sendMessage function takes the input value, sends it via socket.send(), displays it locally, and clears the input.addMessage helper function appends messages to the chat display area.This provides a fundamental, working example of a WebSocket application. You can build upon this by adding features like usernames, chat rooms, JSON message formatting, error handling, reconnection logic, etc.