4bnode
Version:
A professional tool to generate a Node.js app by 4Brains Technologies
83 lines (68 loc) • 2.14 kB
JavaScript
import { WebSocketServer } from 'ws';
import http from 'http';
import express from "express";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import path from "path";
import cors from "cors";
import os from "os";
const env = process.env.NODE_ENV || "development";
dotenv.config({ path: `.env.${env}` });
const app = express();
const port = process.env.PORT || 3000;
// Middleware
const server = http.createServer(app);
const wsServer = new WebSocketServer({ server });
console.log(`WebSocket server is running on the same port as the server (${port})`);
wsServer.on('connection', (ws) => {
console.log('A client connected');
ws.on('message', (message) => {
try {
const parsedMessage = JSON.parse(message);
console.log('Received:', parsedMessage);
// Broadcast to all clients except sender
wsServer.clients.forEach((client) => {
if (client !== ws && client.readyState === ws.OPEN) {
client.send(JSON.stringify(parsedMessage));
}
});
} catch (error) {
console.error('Invalid message format:', error);
}
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
app.use((req, res, next) => {
req.wss = wsServer;
next();
});
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
app.use(cors({ origin: "*" }));
// Serve static files from the public directory
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "public")));
// Get local network IP address
function getLocalNetworkIp() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === "IPv4" && !iface.internal) {
return iface.address;
}
}
}
return null;
}
// Start server
server.listen(port, () => {
const localIp = getLocalNetworkIp();
console.log(`App is running on http://localhost:${port}`);
if (localIp) {
console.log(
`App is also accessible on your local network at http://${localIp}:${port}`
);
}
});