Skip to content

Commit

Permalink
generate room code and client connect
Browse files Browse the repository at this point in the history
  • Loading branch information
Oceankoh committed Jan 20, 2024
1 parent 3d65934 commit 8152cf2
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 60 deletions.
17 changes: 17 additions & 0 deletions backend/client-test/client-connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

import socketClusterClient from 'socketcluster-client';

// Initiate the connection to the server
let socket = socketClusterClient.create({ hostname: 'localhost', port: '8000', path: '/socketcluster/NFHHHQ'});

(async () => {
for await (let { error } of socket.listener('error')) {
console.error(error);
}
})();

(async () => {
for await (let event of socket.listener('connect')) {
console.log('Socket is connected');
}
})();
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"scripts": {
"start": "node server.js",
"start:watch": "./node_modules/nodemon/bin/nodemon.js server.js",
"start:docker": "./node_modules/nodemon/bin/nodemon.js /usr/src/app/server.js"
"start:docker": "./node_modules/nodemon/bin/nodemon.js /usr/src/app/server.js",
"client-connect": "node client-test/client-connect.js"
}
}
2 changes: 1 addition & 1 deletion backend/public/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { create } from '/socketcluster-client.min.js';

// Initiate the connection to the server
let socket = create();
let socket = create({ path: '/socketcluster/ABCABC'});

(async () => {
for await (let { error } of socket.listener('error')) {
Expand Down
99 changes: 41 additions & 58 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,67 @@
import http from 'http';
import eetase from 'eetase';
import socketClusterServer from 'socketcluster-server';
import express from 'express';
import serveStatic from 'serve-static';
import path from 'path';
import morgan from 'morgan';
import { v4 as uuidv4 } from 'uuid';
import sccBrokerClient from 'scc-broker-client';
import { fileURLToPath } from 'url';
import 'dotenv';
import http from "http";
import eetase from "eetase";
import socketClusterServer from "socketcluster-server";
import express from "express";
import serveStatic from "serve-static";
import path from "path";
import morgan from "morgan";
import { fileURLToPath } from "url";
import { generateRoomCode } from "./utils/calc.js";
import { debugServerLogs } from "./utils/debug.js";
import "dotenv";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const ENVIRONMENT = process.env.ENV || 'dev';
const ENVIRONMENT = process.env.ENV || "dev";
const SOCKETCLUSTER_PORT = process.env.SOCKETCLUSTER_PORT || 8000;
const SOCKETCLUSTER_LOG_LEVEL = process.env.SOCKETCLUSTER_LOG_LEVEL || 2;

let agOptions = {};

if (process.env.SOCKETCLUSTER_OPTIONS) {
let envOptions = JSON.parse(process.env.SOCKETCLUSTER_OPTIONS);
Object.assign(agOptions, envOptions);
let envOptions = JSON.parse(process.env.SOCKETCLUSTER_OPTIONS);
Object.assign(agOptions, envOptions);
}

let httpServer = eetase(http.createServer());
let agServer = socketClusterServer.attach(httpServer, agOptions);

let expressApp = express();
if (ENVIRONMENT === 'dev') {
// Log every HTTP request. See https://github.com/expressjs/morgan for other
// available formats.
expressApp.use(morgan('dev'));
if (ENVIRONMENT === "dev") {
expressApp.use(morgan("dev"));
}
expressApp.use(serveStatic(path.resolve(__dirname, 'public')));
expressApp.use(serveStatic(path.resolve(__dirname, "public")));

// Add GET /health-check express route
expressApp.get('/health-check', (req, res) => {
res.status(200).send('OK');
expressApp.get("/health-check", (req, res) => {
res.status(200).send("OK");
});

// HTTP request handling loop.
(async () => {
for await (let requestData of httpServer.listener('request')) {
expressApp.apply(null, requestData);
}
})();
// create-room express route
expressApp.get("/create-room", (req, res) => {
const roomCode = generateRoomCode();
console.log(roomCode);
let agServer = socketClusterServer.attach(httpServer, {
path: "/socketcluster/" + roomCode,
});

// SocketCluster/WebSocket connection handling loop.
(async () => {
for await (let { socket } of agServer.listener('connection')) {
// Handle socket connection.
}
})();
// SocketCluster/WebSocket connection handling loop.
(async () => {
for await (let { socket } of agServer.listener("connection")) {
// Handle socket connection.
}
})();

httpServer.listen(SOCKETCLUSTER_PORT);
debugServerLogs(2, agServer);

if (SOCKETCLUSTER_LOG_LEVEL >= 1) {
(async () => {
for await (let { error } of agServer.listener('error')) {
console.error(error);
}
})();
}

if (SOCKETCLUSTER_LOG_LEVEL >= 2) {
console.log(
` ${colorText('[Active]', 32)} SocketCluster worker with PID ${process.pid} is listening on port ${SOCKETCLUSTER_PORT}`
);
res.status(200).json({ roomCode });
});

(async () => {
for await (let { warning } of agServer.listener('warning')) {
console.warn(warning);
// HTTP request handling loop.
(async () => {
for await (let requestData of httpServer.listener("request")) {
expressApp.apply(null, requestData);
}
})();
}
})();

function colorText(message, color) {
if (color) {
return `\x1b[${color}m${message}\x1b[0m`;
}
return message;
}
httpServer.listen(SOCKETCLUSTER_PORT);
11 changes: 11 additions & 0 deletions backend/utils/calc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Generate a random 6-letter room code
export function generateRoomCode() {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let roomCode = "";
for (let i = 0; i < 6; i++) {
roomCode += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
return roomCode;
}
30 changes: 30 additions & 0 deletions backend/utils/debug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
function colorText(message, color) {
if (color) {
return `\x1b[${color}m${message}\x1b[0m`;
}
return message;
}

export function debugServerLogs(logLevel, agServer) {
if (logLevel >= 1) {
(async () => {
for await (let { error } of agServer.listener("error")) {
console.error(error);
}
})();
}

if (logLevel >= 2) {
console.log(
` ${colorText("[Active]", 32)} SocketCluster worker with PID ${
process.pid
} is listening on port ${process.env.SOCKETCLUSTER_PORT}`
);

(async () => {
for await (let { warning } of agServer.listener("warning")) {
console.warn(warning);
}
})();
}
}

0 comments on commit 8152cf2

Please sign in to comment.