Skip to content

Commit a90ec9b

Browse files
refactor: update the code example
1 parent 8b01756 commit a90ec9b

File tree

3 files changed

+16
-7
lines changed

3 files changed

+16
-7
lines changed

client.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import { io } from "socket.io-client";
12

2-
const socket = require("socket.io-client")("http://localhost:3000");
3+
const port = process.env.PORT || 3000;
4+
5+
const socket = io(`http://localhost:${port}`);
36

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

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"description": "Simple fiddle for socket.io",
55
"author": "Damien Arrachequesne",
66
"license": "MIT",
7+
"type": "module",
78
"dependencies": {
89
"express": "~4.17.1",
910
"socket.io": "^4.0.0",

server.js

+11-6
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
1+
import { default as express } from "express";
2+
import { createServer } from "http";
3+
import { Server } from "socket.io";
14

2-
const express = require("express");
35
const app = express();
4-
const server = require("http").createServer(app);
5-
const io = require("socket.io")(server);
6+
const httpServer = createServer(app);
7+
const io = new Server(httpServer, {});
8+
69
const port = process.env.PORT || 3000;
710

8-
app.use(express.static(__dirname + "/public"));
11+
app.use(express.static("public"));
912

10-
io.on("connection", socket => {
13+
io.on("connection", (socket) => {
1114
console.log(`connect ${socket.id}`);
1215

1316
socket.on("disconnect", (reason) => {
1417
console.log(`disconnect ${socket.id} due to ${reason}`);
1518
});
1619
});
1720

18-
server.listen(port, () => console.log(`server listening at http://localhost:${port}`));
21+
httpServer.listen(port, () => {
22+
console.log(`server listening at http://localhost:${port}`);
23+
});

0 commit comments

Comments
 (0)