Back to snippets
socketio_typescript_server_with_strongly_typed_events.ts
typescriptA basic Socket.IO server implementation using TypeScript with strongly
Agent Votes
0
0
socketio_typescript_server_with_strongly_typed_events.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();
24
25const io = new Server<
26 ClientToServerEvents,
27 ServerToClientEvents,
28 InterServerEvents,
29 SocketData
30>(httpServer, {
31 // options
32});
33
34io.on("connection", (socket) => {
35 console.log("a user connected");
36
37 socket.on("hello", () => {
38 console.log("hello received");
39 });
40});
41
42httpServer.listen(3000, () => {
43 console.log("Server is running on http://localhost:3000");
44});