Skip to content

Commit

Permalink
docs(examples): add example with TypeScript
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
darrachequesne committed Oct 15, 2020
1 parent 20ea6bd commit a81b9f3
Show file tree
Hide file tree
Showing 4 changed files with 343 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/typescript/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Manager } from "socket.io-client";

const manager = new Manager("ws://localhost:8080", {});
const socket = manager.socket("/");

// @ts-ignore
socket.on("connect", () => {
console.log(`connect ${socket.id}`);
});

// @ts-ignore
socket.on("disconnect", () => {
console.log(`disconnect`);
});

setInterval(() => {
const start = Date.now();
socket.emit("ping", () => {
console.log(`pong (latency: ${Date.now() - start} ms)`);
});
}, 1000);
289 changes: 289 additions & 0 deletions examples/typescript/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "typescript",
"version": "1.0.0",
"description": "An example with TypeScript",
"private": true,
"scripts": {
"start:server": "ts-node server.ts",
"start:client": "ts-node client.ts"
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"socket.io": "beta",
"socket.io-client": "beta",
"ts-node": "^9.0.0"
}
}
16 changes: 16 additions & 0 deletions examples/typescript/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Server } from "socket.io";

const io = new Server(8080);

io.on("connect", (socket) => {
console.log(`connect ${socket.id}`);

socket.on("ping", (cb) => {
console.log("ping");
cb();
});

socket.on("disconnect", () => {
console.log(`disconnect ${socket.id}`);
});
});

0 comments on commit a81b9f3

Please sign in to comment.