Skip to content

Instantly share code, notes, and snippets.

@hieptl
Created September 13, 2022 10:31
Show Gist options
  • Save hieptl/dacbcf62e4bb5c50bb4330ea77e809c7 to your computer and use it in GitHub Desktop.
Save hieptl/dacbcf62e4bb5c50bb4330ea77e809c7 to your computer and use it in GitHub Desktop.
Node.js Socket.io - server.js - 1
var http = require("http");
var fs = require("fs");
var path = require("path");
const APP_PORT = process.env.APP_PORT || 3000;
const app = http.createServer(requestHandler);
app.listen(APP_PORT);
console.log(`🖥 HTTP Server running at ${APP_PORT}`);
// handles all http requests to the server
function requestHandler(request, response) {
console.log(`🖥 Received request for ${request.url}`);
// append /client to serve pages from that folder
var filePath = "./client" + request.url;
if (filePath == "./client/") {
// serve index page on request /
filePath = "./client/index.html";
}
var extname = String(path.extname(filePath)).toLowerCase();
console.log(`🖥 Serving ${filePath}`);
var mimeTypes = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpg",
".gif": "image/gif",
".svg": "image/svg+xml",
};
var contentType = mimeTypes[extname] || "application/octet-stream";
fs.readFile(filePath, function (error, content) {
if (error) {
if (error.code == "ENOENT") {
fs.readFile("./client/404.html", function (error, content) {
response.writeHead(404, { "Content-Type": contentType });
response.end(content, "utf-8");
});
} else {
response.writeHead(500);
response.end("Sorry, there was an error: " + error.code + " ..\n");
}
} else {
response.writeHead(200, { "Content-Type": contentType });
response.end(content, "utf-8");
}
});
}
// SOCKET.IO CHAT EVENT HANDLING
const io = require("socket.io")(app, {
path: "/socket.io",
});
io.attach(app, {
// includes local domain to avoid CORS error locally
// configure it accordingly for production
cors: {
origin: "http://localhost",
methods: ["GET", "POST"],
credentials: true,
transports: ["websocket", "polling"],
},
allowEIO3: true,
});
io.on("connection", (socket) => {
console.log("👾 New socket connected! >>", socket.id);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment