Node.js and Socket.io in Action All In One
Node.js and Socket.io in Action All In One
HTTPS / WSS
socket.io
server side
$ npm i socket.io
io.on('connection', socket => {
socket.emit('request', /* … */); // emit an event to the socket
io.emit('broadcast', /* … */); // emit an event to all connected sockets
socket.on('reply', () => { /* … */ }); // listen to the event
});
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
https://www.npmjs.com/package/socket.io
https://github.com/socketio/socket.io
docs
socket.io-client
client side
import { io } from "socket.io-client";
<script type="module">
import { io } from "https://cdn.socket.io/4.3.2/socket.io.esm.min.js";
</script>
https://github.com/socketio/socket.io-client
The Socket instance
(client-side)
A Socket is the fundamental class for interacting with the server.
It inherits most of the methods of the Node.js EventEmitter
, like emit
, on, once or off.
Lifecycle
https://socket.io/docs/v4/client-socket-instance/
demos
server.js
import http from "node:http";
// import https from "node:https";
import fs from 'node:fs';
import express from "express";
import {Server} from "socket.io";
const app = express();
app.use(express.static(`public`));
// http://localhost:3000/index.html
// https://localhost:443/index.html
// app.get(`/socket`, (req, res) => {
// const json = {
// msg: "socket.io message 👻",
// }
// res.json(json);
// });
// http://localhost:3000/socket
// https
// const options = {
// key: fs.readFileSync('./localhost.key'),
// cert: fs.readFileSync('./localhost.crt'),
// };
// const server = https.createServer(options, app);
const server = http.createServer(app);
// const io = new Server(server);
const io = new Server({
path: "/socket",
});
// const io = new Server({
// serveClient: false,
// });
io.on("connection", socket => {
// socket.emit('request', /* … */); // emit an event to the socket
// io.emit('broadcast', /* … */); // emit an event to all connected sockets
// socket.on('reply', () => { /* … */ }); // listen to the event
console.log(`✅ server connection`, socket.id);
socket.emit('send-custom-msg');
setTimeout(() => {
console.log(`socket send 🎉`)
io.emit('send-custom-msg', {
msg: "hello world!",
});
}, 3 * 1000);
// custom event
socket.on("send-custom-msg", (...args) => {
console.log(`✅ server get message =`, args);
});
});
// ❓
io.attach(server);
// const port = process.env.PORT || 443;
const port = process.env.PORT || 3000;
// server.listen(port);
server.listen(port, () => {
console.log(`http server is running on: http://localhost:${port}/`);
});
client.js
// Socket.IO is `NOT` a `WebSocket` implementation. ❌
// https://socket.io/docs/v4/#what-socketio-is-not
// import { io } from "https://cdn.socket.io/4.7.2/socket.io.js";
// import { io } from "https://cdn.socket.io/4.7.2/socket.io.min.js";
// import { io } from "https://cdn.socket.io/4.7.2/socket.io.msgpack.min.js";
import { io } from "https://cdn.socket.io/4.7.2/socket.io.esm.min.js";
// https://cdn.socket.io/4.7.2/
localStorage.debug = 'socket.io-client:socket';
// HTTP / HTTPS ✅
// const socket = io("http://localhost:3000/socket");
// const socket = io("https://localhost:3000/socket");
// WS / WSS ❌
// const socket = io("ws://localhost:3000/socket");
// const socket = io("wss://localhost:3000/socket");
const socket = io("http://localhost:3000/", {
path: "/socket",
});
socket.on("connect", () => {
console.log(`👻 client connect`, socket.id);
});
socket.on("disconnect", () => {
console.log(`👻 client disconnect`, socket.id);
});
const btn = document.querySelector(`#btn`);
btn.addEventListener(`click`, (e) => {
console.log(`click`, e);
socket.emit("send-custom-msg", "message from client❓");
});
socket.on("send-custom-msg", (...args) => {
console.log(`✅ client get message`, args);
});
warnings ⚠️
Socket.IO is NOT
a WebSocket
implementation. ❌
https://socket.io/docs/v4/#what-socketio-is-not
HTTPS / WSS
import { io } from "https://cdn.socket.io/4.7.2/socket.io.esm.min.js";
// HTTPS ✅
const socket = io("https://localhost:3000/socket");
// WSS ❌
// const socket = io("wss://localhost:3000/socket");
HTTP / WS
import { io } from "https://cdn.socket.io/4.7.2/socket.io.esm.min.js";
// HTTP ✅
const socket = io("http://localhost:3000/socket");
// WS ❌
// const socket = io("ws://localhost:3000/socket");
refs
https://stackoverflow.com/questions/77402555/cant-connect-error-in-socket-ios-websocket-link
©xgqfrms 2012-2025
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17803772.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2022-11-01 HSTS All In One
2022-11-01 如何使用 Keynote 幻灯片制作出精美的 gif 动画图解教程 All In One
2021-11-01 tsconfig ignore All In One
2021-11-01 国内股票开盘收盘时间 All In One
2020-11-01 iPhone 12 导入通讯录排序 Bug
2019-11-01 react hooks & component will unmount & useEffect & clear up
2019-11-01 redux connect function component