colyseus/colyseus-defold/colyseus
Open-source Multiplayer Framework. Run your game servers on Node.js and connect to them via the Defold SDK.
- GitHub: colyseus/colyseus-defold — pinned to
0.18.3- Pick a release from colyseus/colyseus-defold releases and add its Source code (zip) URL (or a packaged
.zipasset, if the library ships one) togame.projectunder[project]dependencies, then Fetch Libraries in the Defold editor. - Run
bunx @defold-typescript/cli resolveto materialize its types. - Import it under a namespace alias of your choice:
import * as colyseus from "colyseus.sdk"
- Pick a release from colyseus/colyseus-defold releases and add its Source code (zip) URL (or a packaged
Variables
Client: ClientConstructor
Creates a client: Client("ws://localhost:2567").
callbacks: CallbacksModule
Returns the schema change callbacks of a room: callbacks(room) or callbacks.get(room).
protocol: { readonly JOIN_ROOM: 10; readonly ERROR: 11; readonly LEAVE_ROOM: 12; readonly ROOM_DATA: 13; readonly ROOM_STATE: 14; readonly ROOM_STATE_PATCH: 15; readonly ROOM_DATA_SCHEMA: 16; readonly ROOM_DATA_BYTES: 17; readonly PING: 18; readonly ROOM_INPUT_RELIABLE: 19; readonly ROOM_INPUT_UNRELIABLE: 20; readonly ROOM_REQUEST: 21; readonly ROOM_RESPONSE: 22; readonly CODE_MASK: 0x1f; readonly MODIFIER_MASK: 0xe0; readonly MODIFIER_TIMED: 0x80; readonly RESPONSE_STATUS: { readonly OK: 0; readonly REJECTED: 1; readonly ERROR: 2; }; readonly HANDSHAKE_SECTION: { readonly INPUT_REFLECTION: 1; readonly INPUT_OPTIONS: 2; }; readonly INPUT_FLAGS: { readonly RENDER_TIME: 1; readonly FIXED_TIMESTEP: 2; readonly PATCH_RATE: 4; readonly SUB_STEPS: 8; readonly RECKON_TIME: 16; }; readonly CLOSE_CODE: { readonly NORMAL_CLOSURE: 1000; readonly GOING_AWAY: 1001; readonly NO_STATUS_RECEIVED: 1005; readonly ABNORMAL_CLOSURE: 1006; readonly CONSENTED: 4000; readonly SERVER_SHUTDOWN: 4001; readonly WITH_ERROR: 4002; readonly FAILED_TO_RECONNECT: 4003; readonly MAY_TRY_RECONNECT: 4010; }; }
The protocol codes the client and the server exchange.
Types
type MatchmakeError = HTTPError | RoomError | WebSocketEvent
type MatchmakeCallback<State = unknown> = (err?: MatchmakeError, room?: Room<State>) => void
type HTTPCallback = (err: HTTPError | undefined, data: unknown) => void
ClientConstructor
ClientConstructor.__call(endpoint_or_settings: string | ClientSettings): Client
Creates a client for a server endpoint.
Parameters
endpoint_or_settings:string | ClientSettings— Aws://,wss://,http://orhttps://URL, or the settings it would parse to.
Returns
Client
ClientConstructor.select_by_latency(this: void, endpoints: Array<string | ClientSettings>, callback: (err?: string, client?: Client) => void, timeout?: number)
Measures the latency of each endpoint and calls back with a client for the fastest.
Parameters
this:voidendpoints:Array<string | ClientSettings>— The endpoints to compare, each a URL or its settings.callback:(err?: string, client?: Client) => void— Receives the fastest endpoint's client, or an error when the list is empty or no endpoint responded.timeout?:number— Seconds to wait for each endpoint (default: 1.5).
ClientSettings
ClientSettings.hostname: string
The server's host name, without a trailing /.
ClientSettings.port: number
The server's port.
ClientSettings.use_ssl?: boolean
Whether to connect over wss:// and https://.
ClientSettings.pathname?: string
A path prefix the server is mounted under, without a trailing /.
Auth
Auth.on_change(handler: (auth_data: AuthData) => void): () => void
Calls handler every time the user signs in or out. The first call also fetches the
user's data.
Parameters
handler:(auth_data: AuthData) => void
Returns
() => void— A function that removes the handler.
Auth.get_user_data(callback: (err: HTTPError | string | undefined, user_data: unknown) => void)
Fetches the signed-in user's data.
Parameters
callback:(err: HTTPError | string | undefined, user_data: unknown) => void— Receives the data, or"missing auth token"when signed out, or the request's error.
Auth.register_with_email_and_password(email: string, password: string, callback: HTTPCallback)
Registers a user with an email and a password, and signs them in.
Parameters
email:stringpassword:stringcallback:HTTPCallback
Auth.register_with_email_and_password(email: string, password: string, options: HTTPRequestOptions, callback: HTTPCallback)
Registers a user with an email and a password, and signs them in.
Parameters
email:stringpassword:stringoptions:HTTPRequestOptions— Request options, such asheaders, merged into the request.callback:HTTPCallback
Auth.sign_in_with_email_and_password(email: string, password: string, callback: HTTPCallback)
Signs a user in with an email and a password.
Parameters
email:stringpassword:stringcallback:HTTPCallback
Auth.sign_in_anonymously(callback: HTTPCallback)
Signs in an anonymous user.
Parameters
callback:HTTPCallback
Auth.sign_in_anonymously(options: object, callback: HTTPCallback)
Signs in an anonymous user.
Parameters
options:object— Options sent to the server with the request.callback:HTTPCallback
Auth.send_password_reset_email(email: string, callback: HTTPCallback)
Asks the server to email a password reset link.
Parameters
email:stringcallback:HTTPCallback
Auth.sign_in_with_provider(provider_name: string, settings: object | undefined, callback: (err: string, data: undefined) => void)
Not implemented: prints a notice and calls callback with "not_implemented".
Parameters
provider_name:stringsettings:object | undefined— Ignored.callback:(err: string, data: undefined) => void
Auth.sign_out()
Signs the user out, clearing the token.
Auth.token: string | undefined
The session token, saved on the device and sent with every request; undefined when
there is none.
Auth.http: HTTP
The HTTP helper the requests go through.
Auth.settings: { path: string; }
The route settings: path is the server's auth route prefix (default: "auth").
HTTP
HTTP.get(segments: string, callback: HTTPCallback)
Sends a GET request to the route segments.
Parameters
segments:stringcallback:HTTPCallback
HTTP.get(segments: string, options: HTTPRequestOptions, callback: HTTPCallback)
Sends a GET request to the route segments.
Parameters
segments:stringoptions:HTTPRequestOptionscallback:HTTPCallback
HTTP.post(segments: string, callback: HTTPCallback)
Sends a POST request to the route segments.
Parameters
segments:stringcallback:HTTPCallback
HTTP.post(segments: string, options: HTTPRequestOptions, callback: HTTPCallback)
Sends a POST request to the route segments.
Parameters
segments:stringoptions:HTTPRequestOptionscallback:HTTPCallback
HTTP.put(segments: string, callback: HTTPCallback)
Sends a PUT request to the route segments.
Parameters
segments:stringcallback:HTTPCallback
HTTP.put(segments: string, options: HTTPRequestOptions, callback: HTTPCallback)
Sends a PUT request to the route segments.
Parameters
segments:stringoptions:HTTPRequestOptionscallback:HTTPCallback
HTTP.delete(segments: string, callback: HTTPCallback)
Sends a DELETE request to the route segments.
Parameters
segments:stringcallback:HTTPCallback
HTTP.delete(segments: string, options: HTTPRequestOptions, callback: HTTPCallback)
Sends a DELETE request to the route segments.
Parameters
segments:stringoptions:HTTPRequestOptionscallback:HTTPCallback
HTTP.request(method: string, segments: string, callback: HTTPCallback)
Sends a request with method to the route segments.
Parameters
method:stringsegments:stringcallback:HTTPCallback
HTTP.request(method: string, segments: string, options: HTTPRequestOptions, callback: HTTPCallback)
Sends a request with method to the route segments.
Parameters
method:stringsegments:stringoptions:HTTPRequestOptionscallback:HTTPCallback
HTTP.auth_token: string | undefined
The bearer token sent with every request; Auth.token sets it.
HTTPError
HTTPError.status: number
The HTTP status, or 0 when the request never reached a server.
HTTPError.message: string
What went wrong.
HTTPRequestOptions
HTTPRequestOptions.headers?: Record<string, string>
Extra request headers, merged over the JSON defaults.
HTTPRequestOptions.body?: unknown
The request body, sent encoded as JSON.
AuthData
AuthData.token?: string
The session token, or undefined when signed out.
AuthData.user?: unknown
The signed-in user's data, or undefined when signed out.
RoomError
RoomError.code: number
The error code.
RoomError.error: string
The error message.
WebSocketEvent
WebSocketEvent.event: number
One of the websocket.EVENT_* constants.
WebSocketEvent.message?: string
The received data on a message, the error message otherwise.
WebSocketEvent.code?: number
The status code the server closed the connection with, present on a disconnect only.
WebSocketEvent.handshake_response?: unknown
The handshake response information (status, headers), present on a connect.
Room
Room<State = unknown>
Room.on<E extends keyof RoomEvents<State>>(event: E, listener: RoomEvents<State>[E]): RoomEvents<State>[E]
Calls listener every time the room emits event.
Parameters
event:Elistener:RoomEvents<State>[E]
Returns
RoomEvents<State>[E]— The listener, to pass tooff.
Room.once<E extends keyof RoomEvents<State>>(event: E, listener: RoomEvents<State>[E]): RoomEvents<State>[E]
Calls listener the next time the room emits event.
Parameters
event:Elistener:RoomEvents<State>[E]
Returns
RoomEvents<State>[E]— The listener, to pass tooff.
Room.off()
Removes the most recently added listener of every event.
Room.off<E extends keyof RoomEvents<State>>(event: E, listener?: RoomEvents<State>[E])
Removes listener from event, or the most recently added listener of event when
listener is omitted.
Parameters
event:Elistener?:RoomEvents<State>[E]
Room.on_message(type: "*", handler: (message_type: string | number, message: unknown) => void): () => void
Handles every message whose type has no handler of its own.
Parameters
type:"*"handler:(message_type: string | number, message: unknown) => void
Returns
() => void— A function that removes the handler.
Room.on_message<T = unknown>(type: string | number, handler: (message: T) => void): () => void
Handles the messages of one type the server sends, replacing any handler the type had.
Parameters
type:string | number— The message type.handler:(message: T) => void
Returns
() => void— A function that removes the handler.
Room.leave(consented?: boolean)
Leaves the room.
Parameters
consented?:boolean— Whether the leave is deliberate (default:true).falsecloses the connection without telling the server, as a drop would.
Room.ping(callback: (latency: number) => void)
Measures the round trip to the server. Does nothing while the connection is not open.
Parameters
callback:(latency: number) => void— Receives the round trip in whole milliseconds.
Room.input<Data extends object = Record<string, unknown>>(options?: InputOptions<Data>): InputHandle<Data>
Returns the room's input handle, creating it on the first call. Later calls return the same handle and ignore their options.
Parameters
options?:InputOptions<Data>
Returns
InputHandle<Data>
Room.send(message_type: string | number, message?: object | boolean | number | string)
Sends a message to the server, or buffers it while reconnecting.
Parameters
message_type:string | number— The message type the server's room handles.message?:object | boolean | number | string— The payload, encoded with MessagePack.
Room.send_bytes(message_type: string | number, bytes: number[])
Sends raw bytes to the server, or buffers them while reconnecting.
Parameters
message_type:string | number— The message type the server's room handles.bytes:number[]— The bytes, each a number from 0 to 255.
Room.request(message_type: string | number, payload: unknown, callback: (response: unknown, err: unknown) => void, timeout_ms?: number)
Sends a message and waits for the value the server's handler returns. The callback
receives exactly one of response and err: err when the handler rejects or
throws, the connection closes first, or no reply arrives in time.
Parameters
message_type:string | number— The message type the server's room handles.payload:unknown— The payload, encoded with MessagePack.callback:(response: unknown, err: unknown) => void— Receives the response, or the error.timeout_ms?:number— Milliseconds to wait for the reply (default: 10000).
Room.state: State
The room's synchronized state.
Room.session_id: string
This client's session id in the room.
Room.room_id: string
The room's id.
Room.name: string
The room's name.
Room.connection: Connection
The room's websocket connection.
Room.reconnection: ReconnectionSettings
The automatic reconnection settings.
Room.reconnection_token: ReconnectionToken
What Client.reconnect takes to rejoin this room.
Connection
Connection.on<E extends keyof ConnectionEvents>(event: E, listener: ConnectionEvents[E]): ConnectionEvents[E]
Calls listener every time the connection emits event.
Parameters
event:Elistener:ConnectionEvents[E]
Returns
ConnectionEvents[E]— The listener, to pass tooff.
Connection.once<E extends keyof ConnectionEvents>(event: E, listener: ConnectionEvents[E]): ConnectionEvents[E]
Calls listener the next time the connection emits event.
Parameters
event:Elistener:ConnectionEvents[E]
Returns
ConnectionEvents[E]— The listener, to pass tooff.
Connection.off()
Removes the most recently added listener of every event.
Connection.off<E extends keyof ConnectionEvents>(event: E, listener?: ConnectionEvents[E])
Removes listener from event, or the most recently added listener of event when
listener is omitted.
Parameters
event:Elistener?:ConnectionEvents[E]
Connection.send(data: string)
Sends data over the websocket. Does nothing while the connection is not open.
Parameters
data:string
Connection.open(endpoint: string)
Connects to endpoint. Does nothing when the connection is already open.
Parameters
endpoint:string
Connection.reconnect(query_params: Record<string, string | number>)
Connects again to the last endpoint, replacing its reconnection query parameters.
Parameters
query_params:Record<string, string | number>— The query parameters to append.
Connection.close(close_code?: number)
Closes the connection.
Parameters
close_code?:number— The code thecloseevent reports, for testing reconnection.
Connection.state: "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED"
The connection's state.
ConnectionEvents
ConnectionEvents.open: () => void
The websocket connected.
ConnectionEvents.close: (event: WebSocketEvent) => void
The websocket closed.
ConnectionEvents.error: (event: WebSocketEvent) => void
The websocket failed.
ConnectionEvents.message: (message: string) => void
A message arrived.
ReconnectionSettings
ReconnectionSettings.enabled: boolean
Whether the room reconnects after a drop (default: true).
ReconnectionSettings.retry_count: number
The number of the current reconnection attempt.
ReconnectionSettings.max_retries: number
The attempts made before the room gives up and leaves (default: 15).
ReconnectionSettings.delay: number
The base delay backoff scales, in milliseconds (default: 100).
ReconnectionSettings.min_delay: number
The shortest delay between attempts, in milliseconds (default: 100).
ReconnectionSettings.max_delay: number
The longest delay between attempts, in milliseconds (default: 5000).
ReconnectionSettings.min_uptime: number
How long the room must have been joined before a drop reconnects, in milliseconds (default: 5000).
ReconnectionSettings.backoff: (attempt: number, delay: number) => number
Computes the delay before an attempt from its number and delay (default: exponential).
ReconnectionSettings.max_enqueued_messages: number
How many outgoing messages are buffered while disconnected (default: 10).
ReconnectionSettings.enqueued_messages: { data: string; }[]
The outgoing messages buffered while disconnected, sent once reconnected.
ReconnectionSettings.is_reconnecting: boolean
Whether a reconnection is in progress.
ReconnectionToken
ReconnectionToken.room_id: string
The id of the room to rejoin.
ReconnectionToken.reconnection_token: string
The token the server issued when the room was joined.
RoomEvents
RoomEvents<State = unknown>
RoomEvents.join: () => void
The room was joined.
RoomEvents.reconnect: (retry_count: number) => void
The room reconnected after a drop.
RoomEvents.drop: (event: WebSocketEvent) => void
The connection dropped with a code that allows reconnecting, and reconnection starts.
RoomEvents.leave: (event?: WebSocketEvent | { code: number; }) => void
The room was left. Receives the websocket's close data when the server closed the
connection, { code } when reconnection gave up or was disabled, and nothing when
leave was called on a closed connection.
RoomEvents.error: (error: RoomError | WebSocketEvent) => void
The server sent an error, or the websocket failed.
RoomEvents.statechange: (state: State) => void
The state changed.
InputOptions
InputOptions<Data extends object>
InputOptions.type?: object
The input schema class. Optional when the server room called defineInput().
InputOptions.mode?: "reliable" | "unreliable"
"reliable" (the default) sends one delta per send; "unreliable" sends a ring of
the latest deltas, over the same websocket.
InputOptions.history_size?: number
The size of the "unreliable" ring (default: 3).
InputOptions.render_delay?: number
How far in the past this client draws remote entities, in milliseconds.
InputOptions.allow_rewind?: (data: Data) => boolean
Decides, per reliable send, whether the input carries a lag-compensation stamp.
InputHandle
InputHandle<Data extends object = Record<string, unknown>>
InputHandle.render_delay(): number
How far in the past this client draws remote entities, in milliseconds. A lag-compensating server rewinds its targets by this much plus half the round trip.
Returns
number
InputHandle.set_render_delay(ms?: number)
Sets how far in the past this client draws remote entities.
Parameters
ms?:number— The delay in milliseconds;0when omitted or negative.
InputHandle.pending_count(): number
The number of inputs sent but not yet acknowledged.
Returns
number
InputHandle.send(): number
Encodes the staged input and sends it. Sends one input on every call while the connection is open, an empty frame when nothing changed.
Returns
number— The sequence number assigned to the input, or0when nothing was sent.
InputHandle.on_send(listener: (seq: number) => void): () => void
Calls listener with the sequence number at the end of each send.
Parameters
listener:(seq: number) => void
Returns
() => void— A function that unsubscribes the listener.
InputHandle.reset()
Resets the encoder and the round-trip state, as a reconnection does: the next send
transmits a full snapshot.
InputHandle.at(seq: number): Data | undefined
The buffered snapshot of reliable input seq, for replaying it during
reconciliation. The instance is reused, so read it right away.
Parameters
seq:number
Returns
Data | undefined— The snapshot, orundefinedwhenseqis acknowledged, unsent, or aged out.
InputHandle.reckon_time_at(seq: number): number
The server-clock instant, in milliseconds, stamped onto reliable input seq.
Parameters
seq:number
Returns
number— The instant, or0when reckon stamping is off orseqis out of range.
InputHandle.ack_input(seq: number): number
Records the last input sequence number the server processed.
Parameters
seq:number
Returns
number— The round-trip sample for that acknowledgement in milliseconds, or-1when it is unknown.
InputHandle.data: Data
The staged input: change its fields, then call send.
SeatReservation
SeatReservation.name: string
The room's name.
SeatReservation.roomId: string
The room's id.
SeatReservation.sessionId: string
The session id reserved for this client.
SeatReservation.processId: string
The id of the server process the room runs in.
SeatReservation.publicAddress?: string
The address to connect to instead of the client's own endpoint.
SeatReservation.reconnectionToken?: string
A reconnection token, when the seat rejoins a room.
CallbacksModule
CallbacksModule.__call<State>(room: Room<State>): Callbacks
Returns the schema change callbacks of a joined room's state.
Parameters
room:Room<State>
Returns
Callbacks
CallbacksModule.get<State>(this: void, room: Room<State>): Callbacks
Returns the schema change callbacks of a joined room's state, as calling the module does.
Parameters
this:voidroom:Room<State>
Returns
Callbacks
Callbacks
Callbacks.on_add<T = unknown, K = unknown>(field: string, callback: (value: T, key: K) => void, immediate?: boolean): () => void
Calls callback for each item added to the collection field of the root state.
Parameters
field:stringcallback:(value: T, key: K) => voidimmediate?:boolean— Whether to call it at once for the items already there (default:true).
Returns
() => void— A function that removes the callback.
Callbacks.on_add<T = unknown, K = unknown>(instance: object, field: string, callback: (value: T, key: K) => void, immediate?: boolean): () => void
Calls callback for each item added to the collection field of instance.
Parameters
instance:objectfield:stringcallback:(value: T, key: K) => voidimmediate?:boolean— Whether to call it at once for the items already there (default:true).
Returns
() => void— A function that removes the callback.
Callbacks.on_change<T = unknown, K = unknown>(field: string, callback: (value: T, key: K) => void): () => void
Calls callback for each item that changes in the collection field of the root
state.
Parameters
field:stringcallback:(value: T, key: K) => void
Returns
() => void— A function that removes the callback.
Callbacks.on_change<T = unknown, K = unknown>(instance: object, field: string, callback: (value: T, key: K) => void): () => void
Calls callback for each item that changes in the collection field of instance.
Parameters
instance:objectfield:stringcallback:(value: T, key: K) => void
Returns
() => void— A function that removes the callback.
Callbacks.on_change(instance: object, callback: (changes: unknown) => void): () => void
Calls callback once per patch in which any field of instance changed.
Parameters
instance:objectcallback:(changes: unknown) => void
Returns
() => void— A function that removes the callback.
Callbacks.on_remove<T = unknown, K = unknown>(field: string, callback: (value: T, key: K) => void): () => void
Calls callback for each item removed from the collection field of the root state.
Parameters
field:stringcallback:(value: T, key: K) => void
Returns
() => void— A function that removes the callback.
Callbacks.on_remove<T = unknown, K = unknown>(instance: object, field: string, callback: (value: T, key: K) => void): () => void
Calls callback for each item removed from the collection field of instance.
Parameters
instance:objectfield:stringcallback:(value: T, key: K) => void
Returns
() => void— A function that removes the callback.
Callbacks.listen<T = unknown>(field: string, callback: (value: T, previous_value: T | undefined) => void, immediate?: boolean): () => void
Calls callback whenever the field field of the root state changes.
Parameters
field:stringcallback:(value: T, previous_value: T | undefined) => voidimmediate?:boolean— Whether to call it at once when the field is already set (default:true).
Returns
() => void— A function that removes the callback.
Callbacks.listen<T = unknown>(instance: object, field: string, callback: (value: T, previous_value: T | undefined) => void, immediate?: boolean): () => void
Calls callback whenever the field field of instance changes.
Parameters
instance:objectfield:stringcallback:(value: T, previous_value: T | undefined) => voidimmediate?:boolean— Whether to call it at once when the field is already set (default:true).
Returns
() => void— A function that removes the callback.