Skip to content

Commit a81b9f3

Browse files
docs(examples): add example with TypeScript
There are two issues with the typings: - on the client-side, the Emitter class is not properly imported (hence the @ts-ignore) - on the server-side, the Socket class is not exported (in order to cast it in the "connect" event)
1 parent 20ea6bd commit a81b9f3

File tree

4 files changed

+343
-0
lines changed

4 files changed

+343
-0
lines changed

examples/typescript/client.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Manager } from "socket.io-client";
2+
3+
const manager = new Manager("ws://localhost:8080", {});
4+
const socket = manager.socket("/");
5+
6+
// @ts-ignore
7+
socket.on("connect", () => {
8+
console.log(`connect ${socket.id}`);
9+
});
10+
11+
// @ts-ignore
12+
socket.on("disconnect", () => {
13+
console.log(`disconnect`);
14+
});
15+
16+
setInterval(() => {
17+
const start = Date.now();
18+
socket.emit("ping", () => {
19+
console.log(`pong (latency: ${Date.now() - start} ms)`);
20+
});
21+
}, 1000);

examples/typescript/package-lock.json

Lines changed: 289 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/typescript/package.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"name": "typescript",
3+
"version": "1.0.0",
4+
"description": "An example with TypeScript",
5+
"private": true,
6+
"scripts": {
7+
"start:server": "ts-node server.ts",
8+
"start:client": "ts-node client.ts"
9+
},
10+
"author": "Damien Arrachequesne",
11+
"license": "MIT",
12+
"dependencies": {
13+
"socket.io": "beta",
14+
"socket.io-client": "beta",
15+
"ts-node": "^9.0.0"
16+
}
17+
}

examples/typescript/server.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Server } from "socket.io";
2+
3+
const io = new Server(8080);
4+
5+
io.on("connect", (socket) => {
6+
console.log(`connect ${socket.id}`);
7+
8+
socket.on("ping", (cb) => {
9+
console.log("ping");
10+
cb();
11+
});
12+
13+
socket.on("disconnect", () => {
14+
console.log(`disconnect ${socket.id}`);
15+
});
16+
});

0 commit comments

Comments
 (0)