Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,28 @@
Realtime chat app with websockets using Node.js, Express and Socket.io with Vanilla JS on the frontend with a custom UI
[![Run on Repl.it](https://repl.it/badge/github/bradtraversy/chatcord)](https://repl.it/github/bradtraversy/chatcord)
## Usage

### To start the application

Ensure Docker Desktop is up and running.
See [the Docker website](https://www.docker.com/products/docker-desktop/) to get started.

```
npm install
npm run dev

```
Go to localhost:3000

### To shutdown the application & the Redis image (Docker container)

```
npm run stop
```

### To shutdown the application, Redis image (Docker container) & cleanup Redis volume data

```
npm run docker-down
```

## Notes
Expand Down
12 changes: 12 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: "3"

services:
redis:
image: redis:5
ports:
- "6379:6379"
volumes:
- redis_data:/data

volumes:
redis_data:
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
"description": "Realtime chat app with rooms",
"main": "server.js",
"scripts": {
"start": "node server",
"dev": "nodemon server"
"docker-up": "docker-compose -p chatcord up -d",
"start": "npm run docker-up && node server",
"dev": "npm run docker-up && nodemon server",
"stop": "docker-compose -p chatcord down",
"docker-down": "docker-compose -p chatcord down -v --rmi all"
},
"author": "Brad Traversy",
"license": "MIT",
Expand Down
56 changes: 52 additions & 4 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,60 @@ const io = socketio(server);
app.use(express.static(path.join(__dirname, "public")));

const botName = "ChatCord Bot";
let pubClient, subClient;

(async () => {
pubClient = createClient({ url: "redis://127.0.0.1:6379" });
await pubClient.connect();
subClient = pubClient.duplicate();
io.adapter(createAdapter(pubClient, subClient));
try {
pubClient = createClient({ url: "redis://127.0.0.1:6379" });
await pubClient.connect();
subClient = pubClient.duplicate();
io.adapter(createAdapter(pubClient, subClient));
console.log("Successfully connected to Redis adapter");
} catch (err) {
if (err.code === 'ECONNREFUSED') {
console.warn("Redis server is not available. Make sure it's running.");
} else {
console.error("Error connecting to Redis:", err);
}
}

let reconnectAttempts = 0;
const maxReconnectAttempts = 3;

const handleRedisError = async (err, client) => {
if (err && err.name === 'AbortError') {
console.warn(`${client === pubClient ? 'pubClient' : 'subClient'}: Redis connection aborted.`);
} else if (err && err.errors && err.errors.length > 0) {
const firstError = err.errors[0];
console.warn(`${client === pubClient ? 'pubClient' : 'subClient'}: ${firstError.message}`);
} else {
console.error(`${client === pubClient ? 'pubClient' : 'subClient'} error:`, err);
}

// Reconnect retry mechanism
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
console.log(`Reconnecting ${client === pubClient ? 'pubClient' : 'subClient'} (Attempt ${reconnectAttempts} of ${maxReconnectAttempts})...`);
try {
await client.connect();
console.log(`Successfully reconnected to ${client === pubClient ? 'pubClient' : 'subClient'}`);
reconnectAttempts = 0; // resets the counter if reconnection is successfull
} catch (reconnectError) {
console.error(`Error reconnecting ${client === pubClient ? 'pubClient' : 'subClient'}:`, reconnectError);
}
} else {
console.error(`Max reconnect attempts reached. Shutting down the application.`);
process.exit(1);
}
};

pubClient.on('error', (err) => {
handleRedisError(err, pubClient);
});

subClient.on('error', (err) => {
handleRedisError(err, subClient);
});
})();

// Run when client connects
Expand Down