WebSocket Protocol

The WebSocket protocol enables real-time bidirectional communication between the Unity client and the Node.js server. This allows instant updates when friends come online, send requests, or invite you to games.

Connection

Connection URL Format

ws://localhost:3001/ws?userId=<your_user_id>
wss://api.example.com/friends/ws?userId=<your_user_id>  // Production

Connection Parameters

ParameterRequiredDescription
userIdYesCurrent user's unique identifier

Client to Server Messages

Heartbeat (Keep-Alive)

{
  "type": "heartbeat"
}

Send every 30 seconds to keep the connection alive. Server responds with heartbeat_ack.

Status Update

{
  "type": "status_update",
  "data": {
    "status": "online"
  }
}

Update your online status. Possible values: online, offline, away, in_room

Room Update

{
  "type": "room_update",
  "data": {
    "playerCount": 5
  }
}

Notify about room/game session changes (player count, state).

Server to Client Messages

Connected

{
  "type": "connected",
  "data": {
    "userId": "user123"
  }
}

Sent immediately after successful WebSocket connection.

Friend Request

{
  "type": "friend_request",
  "data": {
    "requestId": "req_abc123",
    "fromUserId": "user456",
    "fromUsername": "PlayerName",
    "timestamp": 1699000000
  }
}

Notifies when someone sends you a friend request.

Friend Status

{
  "type": "friend_status",
  "data": {
    "userId": "friend123",
    "status": "online"
  }
}

Notifies when a friend's status changes.

Invitation

{
  "type": "invitation",
  "data": {
    "id": "inv_xyz789",
    "fromUserId": "friend456",
    "fromUsername": "FriendPlayer",
    "message": "Join my game!",
    "roomInfo": {
      "roomId": "room_abc",
      "roomName": "Awesome Game",
      "playerCount": 2,
      "maxPlayers": 4
    }
  }
}

Notifies when a friend sends you a game invitation.

Heartbeat Ack

{
  "type": "heartbeat_ack"
}

Server response to client heartbeat.

Benefits of WebSocket

FeatureHTTP PollingWebSocket
LatencyDelay until next pollInstant (push)
Server LoadHigher (constant requests)Lower (single connection)
Real-time UpdatesNoYes
Battery ImpactHigherLower
ComplexitySimplerMore complex