Skip to main content

Initialization

Table of content

Creation of a Socket instance

val uri = "https://example.com/socket.io/"

val socket = IO.socket(endpoint)

The scheme part of the URI is also mandatory. Both ws:// and http:// can be used interchangeably.

val socket = IO.socket("https://example.com/socket.io/"); // OK
val socket = IO.socket("wss://example.com/socket.io/"); // OK, similar to the example above
val socket = IO.socket("192.168.0.1:1234/socket.io/"); // NOT OK, missing the scheme part

Connection


socket.onConnect { println("connected") }

socket.onDisconnect { println("disconnected") }

socket.connect()

// socket.disconnect()

Custom Path

It is the name of the path that is captured on the server side.

The server and the client values must match:

JavaScript Server

import { Server } from 'socket.io';

const io = new Server(8080, {
path: '/my-custom-path/',
});

io.on('connection', (socket) => {
// ...
});

Client

val uri = "https://example.com/my-custom-path/"

val socket = IO.socket(endpoint)
info

Please note that this is different from socket-io-client-java works where the path in the URI represents the Namespace.

Query Params

Additional query parameters (then found in socket.handshake.query object on the server-side).

Client

val uri = "https://example.com/socket.io/?x=42"

val socket = IO.socket(endpoint)

JavaScript Server

io.on('connection', (socket) => {
console.log(socket.handshake.query); // prints { x: '42', EIO: '4', transport: 'polling' }
});
info

Please note that this is different from socket-io-client-java works where the query params are passed in IO.Options query

Default values

val options = IOOptions().apply {
forceNew = false
multiplex = true

upgrade = true
rememberUpgrade = true
extraHeaders = null

reconnection = true
reconnectionAttempts = 5
reconnectionDelay = 1000
reconnectionDelayMax = 5000
randomizationFactor = 0.5
timeout = 20000
}

Description

IO factory options

These settings will be shared by all Socket instances attached to the same Manager.

forceNew

Default value: false

Whether to create a new Manager instance.

A Manager instance is in charge of the low-level connection to the server (established with HTTP long-polling or WebSocket). It handles the reconnection logic.

A Socket instance is the interface which is used to sends events to — and receive events from — the server. It belongs to a given namespace.

A single Manager can be attached to several Socket instances.

The following example will reuse the same Manager instance for the 3 Socket instances (one single WebSocket connection):

val socket = IO.socket("https://example.com"); // the main namespace
val productSocket = IO.socket("https://example.com", namespace = "product"); // the "product" namespace
val orderSocket = IO.socket("https://example.com", namespace = "order"); // the "order" namespace

The following example will create 3 different Manager instances (and thus 3 distinct WebSocket connections):

val options = IOOptions().apply {
forceNew = true
}

val socket = IO.socket("https://example.com", options); // the main namespace
val productSocket = IO.socket("https://example.com", options, namespace = "product"); // the "product" namespace
val orderSocket = IO.socket("https://example.com", options, namespace = "order"); // the "order" namespace

multiplex

Default value: true

The opposite of forceNew: whether to reuse an existing Manager instance.

Low-level engine options

transports

Default value: listOf("polling", "websocket")

The low-level connection to the Socket.IO server can either be established with:

  • HTTP long-polling: successive HTTP requests (POST for writing, GET for reading)
  • WebSocket

The following example disables the HTTP long-polling transport:

val options = IOOptions().apply {
transports = listOf("websocket")
}
val socket = IO.socket("https://example.com", options);

Note: in that case, sticky sessions are not required on the server side (more information here).

upgrade

Default value: true

Whether the client should try to upgrade the transport from HTTP long-polling to something better.

rememberUpgrade

Default value: false

If true and if the previous WebSocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try WebSocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets.

extraHeaders

Default value: -

Additional headers (then found in socket.handshake.headers object on the server-side).

Example:

Client

val options = IOOptions.apply {
extraHeaders = mapOf("authorization", "bearer 1234")
}

val socket = IO.socket("https://example.com", options);

JavaScript Server

io.on('connection', (socket) => {
console.log(socket.handshake.headers); // prints { accept: '*/*', authorization: 'bearer 1234', connection: 'Keep-Alive', 'accept-encoding': 'gzip', 'user-agent': 'okhttp/3.12.12' }
});

Manager options

These settings will be shared by all Socket instances attached to the same Manager.

reconnection

Default value: true

Whether reconnection is enabled or not. If set to false, you need to manually reconnect.

reconnectionAttempts

Default value: Integer.MAX_VALUE

The number of reconnection attempts before giving up.

reconnectionDelay

Default value: 1000

The initial delay before reconnection in milliseconds (affected by the randomizationFactor value).

reconnectionDelayMax

Default value: 5000

The maximum delay between two reconnection attempts. Each attempt increases the reconnection delay by 2x.

randomizationFactor

Default value: 0.5

The randomization factor used when reconnecting (so that the clients do not reconnect at the exact same time after a server crash, for example).

Example with the default values:

  • 1st reconnection attempt happens between 500 and 1500 ms (1000 * 2^0 * (<something between -0.5 and 1.5>))
  • 2nd reconnection attempt happens between 1000 and 3000 ms (1000 * 2^1 * (<something between -0.5 and 1.5>))
  • 3rd reconnection attempt happens between 2000 and 5000 ms (1000 * 2^2 * (<something between -0.5 and 1.5>))
  • next reconnection attempts happen after 5000 ms

timeout

Default value: 20000

The timeout in milliseconds for each connection attempt.

Socket options

These settings are specific to the given Socket instance.

Multiplexing

The client does support multiplexing: this allows to split the logic of your application into distinct modules, while using one single WebSocket connection to the server.

Reference: https://socket.io/docs/v4/namespaces/

val socket = IO.socket("https://example.com"); // the main namespace
val productSocket = IO.socket("https://example.com", namespace="product"); // the "product" namespace
val orderSocket = IO.socket("https://example.com", namespace="order"); // the "order" namespace

// All 3 sockets share the same Manager