websocket
Module websocket
API
Declarations
Definitions

ballerina/websocket Ballerina library
Functions
addCookies
function addCookies(ClientConfiguration config)
Adds cookies to the custom header.
Parameters
- config ClientConfiguration - Represents the cookies to be added
authenticateResource
function authenticateResource(Service serviceRef)
Uses for declarative auth design, where the authentication/authorization decision is taken
by reading the auth annotations provided in service/resource and the Authorization
header of request.
Parameters
- serviceRef Service - The service reference where the resource locates
Clients
websocket: Caller
Represents a WebSocket caller.
writeTextMessage
Pushes text messages to the connection. If an error occurs while sending the text message to the connection, that message will be lost.
Parameters
- data string - Data to be sent.
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
writeBinaryMessage
function writeBinaryMessage(byte[] data) returns Error?
Pushes binary data to the connection. If an error occurs while sending the binary message to the connection, that message will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
writeMessage
function writeMessage(anydata data) returns Error?
Writes messages to the connection. If an error occurs while sending the message to the connection, that message will be lost.
Parameters
- data anydata - Data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
ping
function ping(byte[] data) returns Error?
Pings the connection. If an error occurs while sending the ping frame to the server, that frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
pong
function pong(byte[] data) returns Error?
Sends a pong message to the connection. If an error occurs while sending the pong frame to the connection, that the frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
close
Closes the connection.
Parameters
- statusCode int? (default 1000) - Status code for closing the connection
- reason string? (default ()) - Reason for closing the connection
- timeout decimal (default 60) - Time to wait (in seconds) for the close frame to be received from the remote endpoint before closing the connection. If the timeout exceeds, then the connection is terminated even though a close frame is not received from the remote endpoint. If the value < 0 (e.g., -1), then the connection waits until a close frame is received. If the WebSocket frame is received from the remote endpoint within the waiting period, the connection is terminated immediately
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
setAttribute
Sets a connection related attribute.
Parameters
- key string - The key, which identifies the attribute
- value Cloneable - The value of the attribute
getAttribute
Gets connection related attribute if any.
Parameters
- key string - The key to identify the attribute
Return Type
- Cloneable? - The attribute related to the given key or
nil
removeAttribute
Removes connection related attribute if any.
Parameters
- key string - The key to identify the attribute
Return Type
- Cloneable? - The attribute related to the given key or
nil
getConnectionId
function getConnectionId() returns string
Gives the connection id associated with this connection.
Return Type
- string - The unique ID associated with the connection
getNegotiatedSubProtocol
function getNegotiatedSubProtocol() returns string?
Gives the subprotocol if any that is negotiated with the client.
Return Type
- string? - The subprotocol if any negotiated with the client or
nil
isSecure
function isSecure() returns boolean
Gives the secured status of the connection.
Return Type
- boolean -
true
if the connection is secure
isOpen
function isOpen() returns boolean
Gives the open or closed status of the connection.
Return Type
- boolean -
true
if the connection is open
websocket: Client
Represents a WebSocket synchronous client endpoint.
Constructor
Initializes the synchronous client when called.
init (string url, *ClientConfiguration config)
- url string - URL of the target service
- config *ClientConfiguration - The configurations to be used when initializing the client
writeTextMessage
Writes text messages to the connection. If an error occurs while sending the text message to the connection, that message will be lost.
Parameters
- data string - Data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
writeBinaryMessage
function writeBinaryMessage(byte[] data) returns Error?
Writes binary data to the connection. If an error occurs while sending the binary message to the connection, that message will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
ping
function ping(byte[] data) returns Error?
Pings the connection. If an error occurs while sending the ping frame to the server, that frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
pong
function pong(byte[] data) returns Error?
Sends a pong message to the connection. If an error occurs while sending the pong frame to the connection, that the frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
close
Closes the connection.
Parameters
- statusCode int? (default 1000) - Status code for closing the connection
- reason string? (default ()) - Reason for closing the connection
- timeout decimal (default 60) - Time to wait (in seconds) for the close frame to be received from the remote endpoint before closing the connection. If the timeout exceeds, then the connection is terminated even though a close frame is not received from the remote endpoint. If the value is < 0 (e.g., -1), then the connection waits until a close frame is received. If the WebSocket frame is received from the remote endpoint within the waiting period, the connection is terminated immediately
Return Type
- Error? - A
websocket:Error
if an error occurs while closing the WebSocket connection
readTextMessage
Reads text messages in a synchronous manner.
Return Type
readBinaryMessage
function readBinaryMessage() returns byte[]|Error
Reads binary data in a synchronous manner.
Return Type
- byte[]|Error - The binary data sent by the server or an
websocket:Error
if an error occurs when receiving
readMessage
function readMessage(typedesc<anydata> targetType) returns targetType|Error
Reads data from the WebSocket connection.
Parameters
- targetType typedesc<anydata> (default <>) - The payload type (sybtype of
anydata
), which is expected to be returned after data binding
Return Type
- targetType|Error - The data sent by the server or a
websocket:Error
if an error occurs when receiving
writeMessage
function writeMessage(anydata data) returns Error?
Writes messages to the connection. If an error occurs while sending the message to the connection, that message will be lost.
Parameters
- data anydata - Data to be sent
Return Type
- Error? - A
websocket:Error
if an error occurs when sending
initEndpoint
function initEndpoint() returns Error?
setAttribute
Sets a connection-related attribute.
Parameters
- key string - The key, which identifies the attribute
getAttribute
Gets connection-related attributes if any.
Parameters
- key string - The key to identify the attribute
removeAttribute
Removes connection related attribute if any.
Parameters
- key string - The key to identify the attribute
getConnectionId
function getConnectionId() returns string
Gives the connection id associated with this connection.
Return Type
- string - The unique ID associated with the connection
getNegotiatedSubProtocol
function getNegotiatedSubProtocol() returns string?
Gives the subprotocol if any that is negotiated with the client.
Return Type
- string? - The subprotocol if any negotiated with the client or
nil
isSecure
function isSecure() returns boolean
Gives the secured status of the connection.
Return Type
- boolean -
true
if the connection is secure
isOpen
function isOpen() returns boolean
Gives the open or closed status of the connection.
Return Type
- boolean -
true
if the connection is open
getHttpResponse
function getHttpResponse() returns Response?
Gives the HTTP response if any received for the client handshake request.
Return Type
- Response? - The HTTP response received from the client handshake request
Service types
websocket: Service
The WebSocket service type.
websocket: UpgradeService
The WebSocket upgrade service type.
websocket: PingPongService
The WebSocket service type to handle ping/pong frames.
Constants
Listeners
websocket: Listener
This is used for creating WebSocket server endpoints. A WebSocket server endpoint is capable of responding to
remote callers. The Listener
is responsible for initializing the endpoint using the provided configurations.
Constructor
Gets invoked during the module initialization to initialize the listener.
init (int|Listener 'listener, *ListenerConfiguration config)
- 'listener int|Listener -
- config *ListenerConfiguration - Configurations for the WebSocket service listener
attach
function attach(UpgradeService websocketService, string[]|string? name) returns error?
Attaches a service to the listener.
Parameters
- websocketService UpgradeService - The service that needs to be attached
Return Type
- error? - An
error
if an error occurred during the service attachment process or else()
'start
function 'start() returns error?
Starts the registered service programmatically.
Return Type
- error? - An
error
if an error occurred during the listener starting process
gracefulStop
function gracefulStop() returns error?
Stops the service listener gracefully. Already-accepted requests will be served before connection closure.
Return Type
- error? - An
error
if an error occurred during the listener stopping process
immediateStop
function immediateStop() returns error?
Stops the service listener immediately. It is not implemented yet.
Return Type
- error? - An
error
if an error occurred during the listener stop process
detach
function detach(UpgradeService websocketService) returns error?
Detaches a WebSocket service from the listener. Note that detaching a WebSocket service would not affect The functionality of the existing connections.
Parameters
- websocketService UpgradeService - The service to be detached
Return Type
- error? - An
error
if one occurred during detaching of a service or else()
Annotations
websocket: ServiceConfig
The annotation which is used to configure a WebSocket service.
Records
websocket: BearerTokenConfig
Represents token for Bearer token authentication.
Fields
- token string - Bearer token for authentication
websocket: ClientConfiguration
Configurations for the WebSocket client. The following fields are inherited from the other configuration records in addition to the client-specific configs. |
Fields
- Fields Included from *CommonClientConfiguration
- subProtocols string[]
- customHeaders map<string>
- readTimeout decimal
- writeTimeout decimal
- secureSocket ClientSecureSocket|()
- maxFrameSize int
- webSocketCompressionEnabled boolean
- handShakeTimeout decimal
- cookies $CompilationError$[]
- auth ClientAuthConfig
- pingPongHandler PingPongService
- retryConfig WebSocketRetryConfig|()
- validation boolean
websocket: ClientSecureSocket
Configures the SSL/TLS options to be used for WebSocket client.
websocket: CommonClientConfiguration
Common client configurations for WebSocket clients.
Fields
- subProtocols string[](default []) - Negotiable sub protocols of the client
- readTimeout decimal(default -1) - Read timeout (in seconds) of the client
- writeTimeout decimal(default -1) - Write timeout (in seconds) of the client
- secureSocket ClientSecureSocket?(default ()) - SSL/TLS-related options
- maxFrameSize int(default 65536) - The maximum payload size of a WebSocket frame in bytes. If this is not set, is negative, or is zero, the default frame size of 65536 will be used
- webSocketCompressionEnabled boolean(default true) - Enable support for compression in the WebSocket
- handShakeTimeout decimal(default 300) - Time (in seconds) that a connection waits to get the response of the WebSocket handshake. If the timeout exceeds, then the connection is terminated with an error. If the value < 0, then the value sets to the default value(300)
- cookies? Cookie[] - An Array of
http:Cookie
- auth? ClientAuthConfig - Configurations related to client authentication
- pingPongHandler? PingPongService - A service to handle the ping/pong frames. Resources in this service gets called on the receipt of ping/pong frames from the server
- retryConfig WebSocketRetryConfig?(default ()) - Retry-related configurations
- validation boolean(default true) - Enable/disable constraint validation
websocket: CredentialsConfig
Represents credentials for Basic Auth authentication.
websocket: FileUserStoreConfig
Represents file user store configurations for Basic Auth authentication.
websocket: FileUserStoreConfigWithScopes
Represents the auth annotation for file user store configurations with scopes.
Fields
- fileUserStoreConfig FileUserStoreConfig - File user store configurations for Basic Auth authentication
websocket: JwtIssuerConfig
Represents JWT issuer configurations for JWT authentication.
websocket: JwtValidatorConfig
Represents JWT validator configurations for JWT authentication.
Fields
- scopeKey string(default "scope") - The key used to fetch the scopes
websocket: JwtValidatorConfigWithScopes
Represents the auth annotation for JWT validator configurations with scopes.
Fields
- jwtValidatorConfig JwtValidatorConfig - JWT validator configurations for JWT authentication
websocket: LdapUserStoreConfig
Represents LDAP user store configurations for Basic Auth authentication.
websocket: LdapUserStoreConfigWithScopes
Represents the auth annotation for LDAP user store configurations with scopes.
Fields
- ldapUserStoreConfig LdapUserStoreConfig - LDAP user store configurations for Basic Auth authentication
websocket: ListenerConfiguration
Provides a set of configurations for HTTP service endpoints.
Fields
- host string(default "0.0.0.0") - The host name/IP of the endpoint
- http1Settings ListenerHttp1Settings(default {}) - Configurations related to HTTP/1.x protocol
- secureSocket? ListenerSecureSocket - The SSL configurations for the service endpoint. This needs to be configured in order to communicate through WSS
- timeout decimal(default 120) - Period of time in seconds that a connection waits for a read/write operation in the initial upgrade request. Use value 0 to disable timeout
- server string?(default ()) - The server name which should appear as a response header
- webSocketCompressionEnabled boolean(default true) - Enable support for compression in WebSocket
- requestLimits RequestLimitConfigs(default {}) - Configurations associated with inbound request size limits
websocket: ListenerHttp1Settings
Provides settings related to HTTP/1.x protocol.
websocket: ListenerSecureSocket
Configures the SSL/TLS options to be used for WebSocket service.
websocket: OAuth2ClientCredentialsGrantConfig
Represents OAuth2 client credentials grant configurations for OAuth2 authentication.
websocket: OAuth2IntrospectionConfig
Represents OAuth2 introspection server configurations for OAuth2 authentication.
Fields
- scopeKey string(default "scope") - The key used to fetch the scopes
websocket: OAuth2IntrospectionConfigWithScopes
Represents the auth annotation for OAuth2 introspection server configurations with scopes.
Fields
- oauth2IntrospectionConfig OAuth2IntrospectionConfig - OAuth2 introspection server configurations for OAuth2 authentication
websocket: OAuth2JwtBearerGrantConfig
Represents OAuth2 JWT bearer grant configurations for OAuth2 authentication.
websocket: OAuth2PasswordGrantConfig
Represents OAuth2 password grant configurations for OAuth2 authentication.
websocket: OAuth2RefreshTokenGrantConfig
Represents OAuth2 refresh token grant configurations for OAuth2 authentication.
websocket: RequestLimitConfigs
Provides inbound request URI, total header and entity body size threshold configurations.
websocket: WebSocketRetryConfig
Retry configurations for WebSocket.
Fields
- maxCount int(default 0) - The maximum number of retry attempts. If the count is zero, the client will retry indefinitely
- interval decimal(default 1) - The number of seconds to delay before attempting to reconnect
- backOffFactor float(default 1.0) - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist
- maxWaitInterval decimal(default 30) - Maximum time of the retry interval in seconds
websocket: WSServiceConfig
Configurations for a WebSocket service.
Fields
- subProtocols string[](default []) - Negotiable sub protocol by the service
- idleTimeout decimal(default 0) - Idle timeout for the client connection. Upon timeout,
onIdleTimeout
resource (if defined) in the server service will be triggered. Note that this overrides thetimeout
config in thewebsocket:Listener
, which is applicable only for the initial HTTP upgrade request
- maxFrameSize int(default 65536) - The maximum payload size of a WebSocket frame in bytes. If this is not set or is negative or zero, the default frame size, which is 65536 will be used
- auth? ListenerAuthConfig[] - Listener authentication configurations
- validation boolean(default true) - Enable/disable constraint validation
- dispatcherKey? string - The key which is going to be used for dispatching to custom remote functions.
- dispatcherStreamId? string - The identifier used to distinguish between requests and their corresponding responses in a multiplexing scenario.
Errors
websocket: AuthError
Defines the Auth error types that returned from the client.
websocket: AuthnError
Defines the authentication error type that returned from the listener.
websocket: AuthzError
Defines the authorization error type that returned from the listener.
websocket: ConnectionClosureError
Raised during failures in connection closure.
websocket: ConnectionError
Raised during connection failures.
websocket: Error
Represents any error related to the WebSocket module.
websocket: HandshakeTimedOut
Raised when the initial WebSocket handshake timed out.
websocket: InvalidContinuationFrameError
Raised when an out of order/invalid continuation frame is received.
websocket: InvalidHandshakeError
Raised during the handshake when the WebSocket upgrade fails.
websocket: PayloadBindingError
Represents an error, which occurred due to payload binding.
websocket: PayloadTooLargeError
Raised when receiving a frame with a payload exceeding the maximum size.
websocket: PayloadValidationError
Represents an error, which occurred due to payload constraint validation.
websocket: ProtocolError
Raised when the other side breaks the protocol.
websocket: ReadTimedOutError
Raised when the client read time out reaches.
websocket: SslError
Raised when the SSL handshake fails.
websocket: UpgradeError
Raised when the WebSocket upgrade is not accepted.
Union types
websocket: ClientAuthConfig
ClientAuthConfig
Defines the authentication configurations for the WebSocket client.
websocket: OAuth2GrantConfig
OAuth2GrantConfig
Represents OAuth2 grant configurations for OAuth2 authentication.
websocket: ListenerAuthConfig
ListenerAuthConfig
Defines the authentication configurations for the WebSocket listener.
Import
import ballerina/websocket;
Metadata
Released date: 5 months ago
Version: 2.13.0
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.11.0
GraalVM compatible: Yes
Pull count
Total: 25414
Current verison: 2
Weekly downloads
Keywords
ws
network
bi-directional
streaming
service
client
Contributors
Dependents