Skip to content

Instantly share code, notes, and snippets.

@IzzleNizzle
Last active April 25, 2023 23:58
Show Gist options
  • Save IzzleNizzle/e58c2c070d9ded2b927bee2c18ab64d1 to your computer and use it in GitHub Desktop.
Save IzzleNizzle/e58c2c070d9ded2b927bee2c18ab64d1 to your computer and use it in GitHub Desktop.
This example demonstrates how to create a React web application that uses WebSockets 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';
let wsUrl = `wss://${window.location.host}/websocket`;
window.location.host.split(':')[0] === 'localhost' && (wsUrl = `ws://localhost:8082`);
const ws = new WebSocket(wsUrl);
function App() {
ws.onmessage = async function (event) {
const newBgColor = await event.data.text()
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} webSocket={ws} />)}
</div>
</div>
</div>
);
}
export default App;
import React from 'react'
export default function FancyButton({ color, webSocket }) {
return (
<button
type="button"
onClick={() => webSocket.send(color)}
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",
"ws": "^8.11.0"
}
}
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 WebSocket = require('ws');
const express = require('express');
const wss = new WebSocket.Server({ port: process.env.WEBSOCKET_PORT || 8082 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
// Broadcast to all clients
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
const app = express();
// Serve static files from the build folder
app.use(express.static('build'));
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
@IzzleNizzle
Copy link
Author

Nodejs-websocket-react

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