C
CoderspaE
/Documentation

WebSocket API

Real-time communication API for live battles, chat, notifications, and collaborative features in CoderspaE platform.

Connection

Endpoint

wss://ws.coderspae.com/v1

Authentication

Include authentication token in connection URL or headers:

// JavaScript
const ws = new WebSocket('wss://ws.coderspae.com/v1?token=YOUR_JWT_TOKEN');

// With Socket.IO
const socket = io('wss://ws.coderspae.com', {
  auth: {
    token: 'YOUR_JWT_TOKEN'
  }
});

Connection Events

ws.onopen = (event) => {
  console.log('Connected to CoderspaE WebSocket');
};

ws.onclose = (event) => {
  console.log('Disconnected:', event.code, event.reason);
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

Message Format

Request Format

{
  "id": "unique-request-id",
  "type": "subscribe",
  "event": "battle:join",
  "data": {
    "battleId": "battle123",
    "difficulty": "medium"
  },
  "timestamp": "2024-01-15T10:30:00Z"
}

Response Format

{
  "id": "unique-request-id",
  "type": "response",
  "event": "battle:joined",
  "success": true,
  "data": {
    "battleId": "battle123",
    "problem": {...},
    "opponent": {...}
  },
  "timestamp": "2024-01-15T10:30:01Z"
}

Battle Events

Join Battle

Request to join a battle room:

// Send
{
  "type": "subscribe",
  "event": "battle:join",
  "data": {
    "difficulty": "medium",
    "language": "python",
    "mode": "quick-battle"
  }
}

// Receive
{
  "type": "event",
  "event": "battle:matched",
  "data": {
    "battleId": "battle123",
    "opponent": {
      "username": "alice_codes",
      "rating": 1456
    },
    "problem": {
      "id": "prob456",
      "title": "Two Sum",
      "difficulty": "medium"
    },
    "timeLimit": 1800
  }
}

Battle Updates

Real-time battle progress:

// Opponent submitted
{
  "type": "event",
  "event": "battle:submission",
  "data": {
    "battleId": "battle123",
    "userId": "opponent_id",
    "status": "submitted",
    "timestamp": "2024-01-15T10:35:00Z"
  }
}

// Battle ended
{
  "type": "event",
  "event": "battle:ended",
  "data": {
    "battleId": "battle123",
    "winner": "user123",
    "results": {
      "user123": { "score": 100, "time": 847 },
      "opponent_id": { "score": 85, "time": 1203 }
    }
  }
}

Code Submission

Submit solution during battle:

// Submit code
{
  "type": "action",
  "event": "battle:submit",
  "data": {
    "battleId": "battle123",
    "code": "def solution(nums, target):\n    # solution code",
    "language": "python"
  }
}

// Execution result
{
  "type": "event",
  "event": "battle:execution_result",
  "data": {
    "battleId": "battle123",
    "testsPassed": 8,
    "totalTests": 10,
    "executionTime": 0.045,
    "memoryUsed": 14.2,
    "errors": []
  }
}

Chat & Communication

Join Chat Channel

// Subscribe to channel
{
  "type": "subscribe",
  "event": "chat:join",
  "data": {
    "channel": "general",
    "battleId": "battle123" // optional for battle chat
  }
}

// Receive message
{
  "type": "event",
  "event": "chat:message",
  "data": {
    "channel": "general",
    "messageId": "msg789",
    "userId": "user123",
    "username": "alice_codes",
    "message": "Good luck everyone!",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

Send Message

{
  "type": "action",
  "event": "chat:send",
  "data": {
    "channel": "general",
    "message": "Hello CoderspaE community!",
    "replyTo": "msg456" // optional
  }
}

Notifications

System Notifications

{
  "type": "event",
  "event": "notification:system",
  "data": {
    "id": "notif123",
    "title": "Server Maintenance",
    "message": "Scheduled maintenance in 30 minutes",
    "priority": "high",
    "action": {
      "type": "redirect",
      "url": "/maintenance"
    }
  }
}

User Notifications

{
  "type": "event",
  "event": "notification:user",
  "data": {
    "id": "notif456",
    "type": "battle_invite",
    "title": "Battle Invitation",
    "message": "alice_codes invited you to a battle",
    "data": {
      "battleId": "battle789",
      "inviterId": "user456",
      "difficulty": "hard"
    },
    "actions": ["accept", "decline"]
  }
}

Team Collaboration

Team Events

// Team member joined
{
  "type": "event",
  "event": "team:member_joined",
  "data": {
    "teamId": "team123",
    "member": {
      "userId": "user789",
      "username": "bob_developer",
      "role": "member"
    }
  }
}

// Team practice session started
{
  "type": "event",
  "event": "team:practice_started",
  "data": {
    "teamId": "team123",
    "sessionId": "session456",
    "topic": "dynamic-programming",
    "participants": ["user123", "user456", "user789"]
  }
}

Code Sharing

// Share code with team
{
  "type": "action",
  "event": "team:share_code",
  "data": {
    "teamId": "team123",
    "problemId": "prob456",
    "code": "def solution():\n    # shared solution",
    "language": "python",
    "note": "Alternative approach using DP"
  }
}

// Code shared notification
{
  "type": "event",
  "event": "team:code_shared",
  "data": {
    "teamId": "team123",
    "sharedBy": "alice_codes",
    "problemId": "prob456",
    "language": "python",
    "note": "Alternative approach using DP"
  }
}

Error Handling

Error Response

{
  "id": "request-id",
  "type": "error",
  "error": {
    "code": "INVALID_BATTLE_ID",
    "message": "Battle not found or already ended",
    "details": {
      "battleId": "invalid123",
      "status": "ended"
    }
  },
  "timestamp": "2024-01-15T10:30:00Z"
}

Common Error Codes

CodeDescriptionAction
UNAUTHORIZEDInvalid or expired tokenRe-authenticate
RATE_LIMITEDToo many requestsImplement backoff
BATTLE_FULLBattle room is fullFind another battle
INVALID_CODECode submission failed validationCheck code syntax

Client Libraries

JavaScript/Node.js

import { CoderspaESocket } from '@coderspae/websocket';

const socket = new CoderspaESocket({
  token: 'your-jwt-token',
  autoReconnect: true
});

socket.on('battle:matched', (data) => {
  console.log('Battle matched:', data);
});

await socket.joinBattle({ difficulty: 'medium' });

Python

import asyncio
from coderspae_websocket import CoderspaESocket

async def main():
    socket = CoderspaESocket(token='your-jwt-token')
    
    @socket.on('battle:matched')
    async def on_battle_matched(data):
        print(f"Battle matched: {data}")
    
    await socket.connect()
    await socket.join_battle(difficulty='medium')

asyncio.run(main())

Go

package main

import (
    "github.com/coderspae/websocket-go"
)

func main() {
    client := websocket.New(websocket.Config{
        Token: "your-jwt-token",
        URL:   "wss://ws.coderspae.com/v1",
    })
    
    client.On("battle:matched", func(data interface{}) {
        fmt.Printf("Battle matched: %v\n", data)
    })
    
    client.Connect()
    client.JoinBattle(map[string]interface{}{
        "difficulty": "medium",
    })
}

Best Practices

Connection Management

  • • Implement exponential backoff for reconnections
  • • Handle connection drops gracefully
  • • Send heartbeat/ping messages periodically
  • • Clean up subscriptions on disconnect

Message Handling

  • • Validate all incoming messages
  • • Implement message deduplication
  • • Use request IDs for tracking
  • • Handle out-of-order messages

Performance

  • • Batch multiple operations when possible
  • • Implement client-side caching
  • • Use compression for large messages
  • • Monitor connection latency