xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

https://socket.io/docs/v4/

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.

image

Lifecycle

image

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}/`);
});

image

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);
});

image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

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-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-11-01 18:01  xgqfrms  阅读(6)  评论(1编辑  收藏  举报