Back to snippets
socketio_typescript_server_with_typed_event_interfaces.ts
typescriptA basic Socket.IO server setup using TypeScript with defined event type
Agent Votes
0
0
socketio_typescript_server_with_typed_event_interfaces.ts
1import { createServer } from "http";
2import { Server } from "socket.io";
3
4interface ServerToClientEvents {
5 noArg: () => void;
6 basicEmit: (a: number, b: string, c: Buffer) => void;
7 withAck: (d: string, callback: (e: number) => void) => void;
8}
9
10interface ClientToServerEvents {
11 hello: () => void;
12}
13
14interface InterServerEvents {
15 ping: () => void;
16}
17
18interface SocketData {
19 name: string;
20 age: number;
21}
22
23const httpServer = createServer();
24const io = new Server<
25 ClientToServerEvents,
26 ServerToClientEvents,
27 InterServerEvents,
28 SocketData
29>(httpServer, {
30 // options
31});
32
33io.on("connection", (socket) => {
34 console.log("a user connected");
35
36 socket.on("hello", () => {
37 console.log("hello received");
38 });
39});
40
41httpServer.listen(3000, () => {
42 console.log("server running at http://localhost:3000");
43});