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.
Below, I'll guide you through creating a simple WebSocket application. This app will be a basic real-time chat application where users can send messages, and they will be broadcasted to all connected clients.
We'll use:
The app will consist of:
websocket-app.npm init -y to create a package.json file.npm install ws.Create a file named server.js in your project directory and add the following code:
const http = require('http');
const fs = require('fs');
const WebSocket = require('ws');
// Create an HTTP server to serve the HTML file
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500);
res.end('Error loading index.html');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404);
res.end('Not found');
}
});
// Create a WebSocket server attached to the HTTP server
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('A new client connected');
// Handle incoming messages
ws.on('message', (message) => {
console.log('Received message: %s', message);
// Broadcast the message to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle client disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
});
// Start the server
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});
This server:
index.html file when you visit http://localhost:8080.In the same project directory, create a file named index.html with 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 App</title>
<style>
#messages {
border: 1px solid #ccc;
padding: 10px;
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Simple WebSocket Chat</h1>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type a message...">
<button id="sendButton">Send</button>
<script>
// Create a WebSocket connection
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to WebSocket server');
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += '<p>Connected to server!</p>';
};
ws.onmessage = (event) => {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += '<p>Received: ' + event.data + '</p>';
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll to bottom
};
ws.onclose = () => {
console.log('Disconnected from WebSocket server');
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += '<p>Disconnected from server.</p>';
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Handle send button click
document.getElementById('sendButton').addEventListener('click', () => {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (message) {
ws.send(message); // Send message to server
input.value = ''; // Clear input field
}
});
</script>
</body>
</html>
This client:
ws://localhost:8080.In your terminal, run the server:
node server.js
You should see: "Server is listening on port 8080".
Open a web browser and go to: http://localhost:8080.
In the browser, type a message in the input field and click "Send". The message will appear in the messages div.
To test real-time functionality:
This is a basic example. For a production app, you'd want to add features like user authentication, error handling, and perhaps a frontend framework like React. If you need modifications or more features, let me know!