Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save IzzleNizzle/59cf7dee409a75eb8368f82753efa422 to your computer and use it in GitHub Desktop.
Save IzzleNizzle/59cf7dee409a75eb8368f82753efa422 to your computer and use it in GitHub Desktop.
This example demonstrates how to create a simple web application using WebSockets (Socket.io NPM Package) to establish real-time communication between a server and a client, allowing messages to be sent and received in real-time.
import rainbowColorsMap from './rainbowColorsMap';
import FancyButton from './FancyButton';
import { io } from 'socket.io-client';
let socket = io({
secure: true,
});
if (window.location.host.split(':')[0] === 'localhost') {
socket = io('http://localhost:3009');
}
function App() {
socket.on('color_change', (newBgColor) => {
document.documentElement.style.setProperty("--main-color", rainbowColorsMap[newBgColor][200].color);
});
return (
<div className="flex justify-center items-center h-screen">
<div className=" flex justify-center items-center flex-col">
<h2 className="mb-4">Press a color 🌈</h2>
<div className="flex justify-center items-stretch flex-col">
{Object.keys(rainbowColorsMap).map((bgColor) => (
<FancyButton key={bgColor} color={bgColor} socket={socket} />
))}
</div>
</div>
</div>
);
}
export default App;
import React from 'react';
export default function FancyButton({ color, socket }) {
const handleClick = () => {
socket.emit('color_change', color);
};
return (
<button
type="button"
onClick={handleClick}
className={`focus:outline-none text-white ${`bg-${color}-${400}`} font-medium rounded-lg text-sm px-5 py-2.5 mb-2`}
>
{color}
</button>
);
}
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"socket.io": "^4.6.1"
}
}
const rainbowColorsMap = {
red: {
200: {
className: "bg-red-200",
color: "rgb(255, 178, 178)",
},
400: {
className: "bg-red-400",
color: "rgb(248, 113, 113)",
},
600: {
className: "bg-red-600",
color: "rgb(198, 48, 48)",
},
},
orange: {
200: {
className: "bg-orange-200",
color: "rgb(255, 209, 158)",
},
400: {
className: "bg-orange-400",
color: "rgb(255, 147, 0)",
},
600: {
className: "bg-orange-600",
color: "rgb(204, 85, 0)",
},
},
yellow: {
200: {
className: "bg-yellow-200",
color: "rgb(255, 253, 152)",
},
400: {
className: "bg-yellow-400",
color: "rgb(255, 230, 0)",
},
600: {
className: "bg-yellow-600",
color: "rgb(178, 135, 0)",
},
},
green: {
200: {
className: "bg-green-200",
color: "rgb(167, 243, 208)",
},
400: {
className: "bg-green-400",
color: "rgb(16, 185, 129)",
},
600: {
className: "bg-green-600",
color: "rgb(0, 128, 96)",
},
},
blue: {
200: {
className: "bg-blue-200",
color: "rgb(179, 229, 252)",
},
400: {
className: "bg-blue-400",
color: "rgb(29, 161, 242)",
},
600: {
className: "bg-blue-600",
color: "rgb(13, 71, 161)",
},
},
indigo: {
200: {
className: "bg-indigo-200",
color: "rgb(196, 181, 253)",
},
400: {
className: "bg-indigo-400",
color: "rgb(92, 78, 204)",
},
600: {
className: "bg-indigo-600",
color: "rgb(57, 43, 128)",
},
},
violet: {
200: {
className: "bg-purple-200",
color: "rgb(223, 197, 255)",
},
400: {
className: "bg-purple-400",
color: "rgb(155, 64, 239)",
},
600: {
className: "bg-purple-600",
color: "rgb(84, 26, 139)",
},
},
};
export default rainbowColorsMap
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
// Serve static files from the build folder
app.use(express.static('build'));
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: '*',
},
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('color_change', (color) => {
console.log(`received: ${color}`);
// Broadcast to all clients
io.emit('color_change', color);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
// Start the server
const port = process.env.PORT || 3009;
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
@IzzleNizzle
Copy link
Author

I found that using the Socket.io npm library to be more stable in keeping the websocket connection alive over time. Less buggy.

Live demo can be found here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment