A real-time messaging server built with Node.js, WebSocket, and Redis PubSub.
- Node.js 18 or higher
- pnpm
- Redis
- MongoDB
pnpm install
Create a .env
file in the root directory with the following variables:
MONGODB_URI=mongodb://localhost:27017/pubsub
REDIS_URL=redis://localhost:6379
PORT=8080
Connect to the WebSocket server with a userId parameter:
const ws = new WebSocket('ws://localhost:8080?userId=user123');
All messages follow this JSON format:
interface WebSocketMessage {
action: string;
[key: string]: any;
}
Request:
{
"action": "syncMessages",
"clientMaxMessageId": "lastMessageId"
}
Response:
{
"action": "syncMessagesResponse",
"messages": [
{
"id": "messageId",
"content": "message content",
"timestamp": "2024-01-01T00:00:00Z"
}
]
}
Request:
{
"action": "joinGroup",
"groupId": "group123",
"role": "member"
}
Response:
{
"action": "joinGroupResponse",
"success": true
}
Request:
{
"action": "sendGroupMessage",
"groupId": "group123",
"content": "Hello, group!",
"isInRole": true
}
When an error occurs, the server responds with:
{
"action": "error",
"error": "Error message description"
}
Start the development server:
pnpm dev
Run with Docker Compose:
docker-compose up -d
This will start:
- The WebSocket server
- Redis
- MongoDB
MIT