docs: add example with NW.js

This commit is contained in:
Damien Arrachequesne
2024-04-12 11:13:31 +02:00
parent 907f102517
commit 14d4997dbc
6 changed files with 121 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
# Socket.IO with [NW.js](https://nwjs.io/)
Guide: https://socket.io/how-to/use-with-nwjs
## How to use
### Client
```bash
# install the dependencies
$ npm i
# start the app
$ nw .
```
### Server
```bash
$ cd server
# install the dependencies
$ npm i
# start the server
$ npm start
```

View File

@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<body>
<p>Status: <span id="status"></span></p>
<p>Transport: <span id="transport"></span></p>
<script>
const { registerListeners, emit } = require("./index");
const statusSpan = document.getElementById("status");
const transportSpan = document.getElementById("transport");
statusSpan.innerText = "Disconnected";
transportSpan.innerText = "N/A";
registerListeners({ statusSpan, transportSpan });
emit("hello", "world");
</script>
</body>
</html>

View File

@@ -0,0 +1,34 @@
const { io } = require("socket.io-client");
const socket = io("http://localhost:3000");
exports.registerListeners = function ({ statusSpan, transportSpan }) {
function onConnect() {
statusSpan.innerText = "Connected";
transportSpan.innerText = socket.io.engine.transport.name;
socket.io.engine.on("upgrade", (transport) => {
transportSpan.innerText = transport.name;
});
console.log(`connect ${socket.id}`);
}
if (socket.connected) {
onConnect();
}
socket.on("connect", onConnect);
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
socket.on("disconnect", (reason) => {
statusSpan.innerText = "Disconnected";
transportSpan.innerText = "N/A";
console.log(`disconnect due to ${reason}`);
});
}
exports.emit = function (...args) {
socket.emit(...args);
}

View File

@@ -0,0 +1,7 @@
{
"name": "helloworld",
"main": "index.html",
"dependencies": {
"socket.io-client": "^4.7.5"
}
}

View File

@@ -0,0 +1,17 @@
import { Server } from 'socket.io';
const io = new Server();
io.on('connection', (socket) => {
console.log(`connect: ${socket.id}`);
socket.on("hello", (val) => {
console.log(val);
});
socket.on('disconnect', () => {
console.log(`disconnect: ${socket.id}`);
});
});
io.listen(3000);

View File

@@ -0,0 +1,15 @@
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"socket.io": "^4.7.5"
}
}