[Node.js] Socket.io and WebSocket
https://btholt.github.io/complete-intro-to-realtime/socketio
https://btholt.github.io/complete-intro-to-realtime/intro-to-websockets
Socket.io:
FE:
const socket = io("http://localhost:8080");
socket.on("connect", () => {
console.log("connected");
presence.innerText = "🟢";
});
socket.on("disconnect", () => {
presence.innerText = "🔴";
});
socket.on("msg:get", (data) => {
allChat = data.msg;
render();
});
chat.addEventListener("submit", function (e) {
e.preventDefault();
postNewMsg(chat.elements.user.value, chat.elements.text.value);
chat.elements.text.value = "";
});
async function postNewMsg(user, text) {
socket.emit("msg:post", { user, text });
}
BE:
import http from "http";
import handler from "serve-handler";
import nanobuffer from "nanobuffer";
import { Server } from "socket.io";
const msg = new nanobuffer(50);
const getMsgs = () => Array.from(msg).reverse();
msg.push({
user: "brian",
text: "hi",
time: Date.now(),
});
// serve static assets
const server = http.createServer((request, response) => {
return handler(request, response, {
public: "./frontend",
});
});
const io = new Server(server, {});
io.on("connection", (socket) => {
console.log(`connected: ${socket.id}`);
// emit the current messages to the new client
socket.emit("msg:get", { msg: getMsgs() });
socket.on("msg:post", (data) => {
msg.push({
user: data.user,
text: data.text,
time: Date.now(),
});
// emit the new message to all clients
io.emit("msg:get", { msg: getMsgs() });
});
socket.on("disconnect", () => {
console.log(`disconnect: ${socket.id}`);
});
});