This is a Node.js implementation of the WebSocket chat application, providing the same functionality as the Go version.
- User authentication with OTP-based login
- Real-time WebSocket communication
- Multiple chat rooms support
- Ping-pong heartbeat mechanism
- Auto-cleanup of expired OTPs
- CORS support for cross-origin requests
- Node.js (v14 or higher)
- npm or yarn
-
Navigate to the nodejs-backend directory:
cd nodejs-backend -
Install dependencies:
npm install
npm run devnpm startThe server will start on port 8080 by default. You can access the application at http://localhost:8080.
Authenticate user and receive OTP for WebSocket connection.
Request body:
{
"username": "balu",
"password": "123"
}Response:
{
"otp": "generated-uuid-string"
}Connect to WebSocket at ws://localhost:8080/ws?otp=YOUR_OTP&name=USERNAME
The following users are pre-configured with password "123":
- balu
- yaswanth
- person1
- person2
{
"type": "send_message",
"payload": {
"message": "Hello, World!",
"from": "username"
}
}{
"type": "change_chatroom",
"payload": {
"name": "room-name"
}
}{
"type": "new_message",
"payload": {
"message": "Hello, World!",
"from": "username",
"sent": "2023-12-07T10:30:00.000Z"
}
}server.js- Main server file with Express and WebSocket setupmanager.js- WebSocket connection manager and event routingclient.js- Individual client connection handlingotp.js- OTP generation and verification systemevents.js- Event type constantspackage.json- Project dependencies and scripts
- OTP-based authentication
- One-time use OTPs with automatic expiration (5 seconds)
- Connection verification before WebSocket upgrade
- Automatic cleanup of expired OTPs
- Uses HTTP instead of HTTPS (can be easily modified for HTTPS)
- Uses
wslibrary instead of Gorilla WebSocket - Express.js for HTTP server instead of Go's net/http
- UUID v4 for OTP generation instead of Google UUID