gpt-4-0314· openai
Suzhen/CodeChat
we want to have 1. a webpage which waits a websocket connection 2. nodejs which monitors…
- User
we want to have
- a webpage which waits a websocket connection
- nodejs which monitors accesslog and once someone enters the page(1) it connects to it via websocket and sends sample message write minimal code please
- Assistant
- Create index.html file for the webpage:
<!DOCTYPE html> <html> <head> <title>Websocket Demo</title> <script> const websocket = new WebSocket('ws://localhost:3000'); websocket.addEventListener('open', (event) => { console.log('Connected to WebSocket Server'); }); websocket.addEventListener('message', (event) => { console.log('Message received from server :', event.data); }); websocket.addEventListener('close', (event) => { console.log('Disconnected from WebSocket Server'); }); </script> </head> <body> <h1>Websocket Demo Page</h1> </body> </html>- Install the required WebSocket package for the Node.js application:
npm install ws- Create a server.js file for the Node.js application:
const fs = require('fs'); const http = require('http'); const WebSocket = require('ws'); // create an HTTP server for serving the HTML file const server = http.createServer((req, res) => { // serve the HTML file whenever a new request is made 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); } }); }); // create a WebSocket server const webSocketServer = new WebSocket.Server({ server }); // listen for connections on the WebSocket server webSocketServer.on('connection', (client) => { console.log('WebSocket connection established'); // check for changes in the access log and send a sample message fs.watch('./access.log', () => { client.send('Sample message received from server'); }); }); const PORT = 3000; const accessLogWriteStream = fs.createWriteStream('./access.log', { flags: 'a' }); // start the HTTP server and log each request to the access log server.listen(PORT, () => { console.log(`Server listening at http://localhost:${PORT}`); }); server.on('request', (req) => { accessLogWriteStream.write(`[${new Date().toISOString()}] ${req.method} ${req.url}\n`); });Now you have a minimal setup for the requested functionality. To test it:
- Run the Node.js server:
node server.js - Open the
index.htmlfile in your browser. - Check the browser console for messages received from the server.
- Check the access.log file for logged requests.