Hello world using websocket
- User
Hello world using websocket
Assistant
Hello World using WebSocket
Here's a simple example of a WebSocket "Hello World" implementation using JavaScript in a browser and a Node.js server.
Client-side (Browser)
<!DOCTYPE html> <html> <head> <title>WebSocket Hello World</title> </head> <body> <h1>WebSocket Hello World</h1> <div id="output"></div> <script> // Create a new WebSocket connection const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', (event) => { socket.send('Hello Server!'); document.getElementById('output').innerHTML += '<p>Message sent to server</p>'; }); // Listen for messages socket.addEventListener('message', (event) => { document.getElementById('output').innerHTML += `<p>Message from server: ${event.data}</p>`; }); // Connection closed socket.addEventListener('close', (event) => { document.getElementById('output').innerHTML += '<p>Connection closed</p>'; }); </script> </body> </html>Server-side (Node.js)
First, install the
wspackage:npm install wsThen create a server file (e.g.,
server.js):const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('New client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); // Send a response back to the client ws.send('Hello Client! This is the server responding to your message: ' + message); }); ws.on('close', () => { console.log('Client disconnected'); }); }); console.log('WebSocket server running on ws://localhost:8080');How to Run
- Save the HTML code to a file (e.g.,
index.html) - Save the Node.js code to
server.js - Run the server:
node server.js - Open the HTML file in a browser
Expected Output
- The browser will connect to the WebSocket server
- The client will send "Hello Server!" to the server
- The server will respond with a message that includes the client's message
- Both messages will be displayed in the browser
This demonstrates a basic WebSocket communication where the client and server exchange messages in real-time.
- Save the HTML code to a file (e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.