Websocket Basics with JavaScript
source link: https://www.devdungeon.com/content/websocket-basics-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Intro
To implement WebSockets, you need a client and a server. Ws.js is a library for Node.js that lets you create servers. For the client side, we'll use the native WebSocket object in the browser.
Server example
You need to install the ws
package with npm
first:
npm install ws
Here is a modified example from https://www.npmjs.com/package/ws#simple-server.
server.js
:
// server.js
// npm install ws
// Run this server and then open client.html in browser
// Reference: https://www.npmjs.com/package/ws#simple-server
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
console.log('Client sent the server: %s', data);
});
ws.send('Greetings, client!');
});
console.log('Running...');
Client example
This example is modified from the Mozilla docs example.
client.html
:
<!-- client.html -->
<!-- https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#examples -->
<html>
<body>
<script>
const socket = new WebSocket('ws://localhost:8080');
// Connect
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Handle server messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
// To send data, use `socket.send()`
</script>
</body>
</html>
References
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK