websocket
ballerina/websocket
Package Overview
This package provides an implementation for connecting and interacting with WebSocket endpoints. The package facilitates three types of network entry points as ‘Client’, ‘AsyncClient’, and ‘Listener’.
The websocket:Client
reads text and binary messages synchronously. A callback service with the two onPing
and onPong
remote functions can be registered at the initialization of the client to receive ping/pong
control frames.
The websocket:AsyncClient
, which behaves asynchronously also has a callback websocket:Service
that can be registered at the initialization of the client. It has a fixed set of remote methods in this service and they get called on the receipt of messages from the server.
On the server-side, an initial WebSocket service is there to handle upgrade requests. It has a single get
resource, which takes in an http:Request
optionally. The get
resource returns a websocket:Service
to which incoming messages get dispatched after a successful WebSocket connection upgrade. This resource can be used to intercept the initial HTTP upgrade with custom headers or to cancel the WebSocket upgrade by returning an error.
The returning websocket:Service
has a fixed set of remote methods.
WebSocket upgrade: During a WebSocket upgrade, the initial message received is an HTTP request.
service /ws on new websocket:Listener(21003) { resource function get .(http:Request req) returns websocket:Service|websocket:UpgradeError { return new WsService(); } service class WsService { *websocket:Service; remote isolated function onTextMessage(websocket:Caller caller, string data) returns websocket:Error? { check caller->writeTextMessage(data); } }
Remote methods associated with websocket:Service
onOpen: As soon as the WebSocket handshake is completed and the connection is established, the onOpen
remote method is dispatched.
onTextMessage: The received text messages are dispatched to this remote method.
onBinaryMessage: The received binary messages are dispatched to this remote method.
onPing and onPong: The received ping and pong messages are dispatched to these remote methods respectively.
onIdleTimeout: This remote method is dispatched when the idle timeout is reached. The idleTimeout
has to be configured either in the WebSocket service or the client configuration.
onClose: This remote method is dispatched when a close frame with a statusCode and a reason is received.
onError: This remote method is dispatched when an error occurs in the WebSocket connection. This will always be preceded by a connection closure with an appropriate close frame.
Remote methods associated with websocket:Client
service
onPing: The received ping
messages are dispatched to this remote method.
onPong: The received pong
messages are dispatched to this remote method.
For more information, see the following.
Listeners
websocket: Listener
This is used for creating Websocket server endpoints. An 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 module initialization to initialize the listener.
init (int|Listener 'listener, *ListenerConfiguration config)
- config *ListenerConfiguration - Configurations for the websocket service listener
attach
Attaches a service to the listener.
Parameters
- s Service - The service that needs to be attached
Return Type
- error? - An
error
an error occurred during the service attachment process or else nil
'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
Detaches a Http or WebSocket service from the listener. Note that detaching a WebSocket service would not affect The functionality of the existing connections.
Parameters
- s Service - The service to be detached
Return Type
- error? - An
error
if one occurred during detaching of a service or else()
initEndpoint
function initEndpoint() returns Error?
Clients
websocket: Caller
Represents a WebSocket caller.
writeTextMessage
Pushes text 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? - An
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? - An
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? - An
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 frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - An
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 WebSocket frame is received from the remote endpoint within the waiting period, the connection is terminated immediately.
Return Type
- Error? - An
error
if an error occurs when sending
setAttribute
function setAttribute(string key, any value)
Sets a connection related attribute.
Parameters
- key string - The key, which identifies the attribute
- value any - The value of the attribute
getAttribute
function getAttribute(string key) returns any
Gets connection related attribute if any.
Parameters
- key string - The key to identify the attribute
Return Type
- any - The attribute related to the given key or
nil
removeAttribute
function removeAttribute(string key) returns any
Removes connection related attribute if any.
Parameters
- key string - The key to identify the attribute
Return Type
- any - 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 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? - An
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? - An
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? - An
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 frame will be lost.
Parameters
- data byte[] - Binary data to be sent
Return Type
- Error? - An
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? - An
error
if an error occurs while closing the WebSocket connection
readTextMessage
Reads the texts in a synchronous manner
Return Type
readBinaryMessage
function readBinaryMessage() returns byte[]|Error
Reads the binary data in a synchronous manner
Return Type
- byte[]|Error - The binary data sent by the server or an
error
if an error occurs when sending
initEndpoint
function initEndpoint() returns Error?
setAttribute
function setAttribute(string key, any value)
Sets a connection-related attribute.
Parameters
- key string - The key, which identifies the attribute
- value any - The value of the attribute
getAttribute
function getAttribute(string key) returns any
Gets connection-related attributes if any.
Parameters
- key string - The key to identify the attribute
Return Type
- any - The attribute related to the given key or
nil
removeAttribute
function removeAttribute(string key) returns any
Removes connection related attribute if any.
Parameters
- key string - The key to identify the attribute
Return Type
- any - 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
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
Functions
addCookies
function addCookies(ClientConfiguration config)
Adds cookies to the custom header.
Parameters
- config ClientConfiguration - Represents the cookies to be added
Object types
websocket: PingPongService
The Websocket Sync client service type
websocket: Service
The Websocket service type
websocket: UpgradeService
The Websocket upgrade service type
Records
websocket: BearerTokenConfig
Represents token for Bearer token authentication.
Fields
- token string - Bearer token for authentication
websocket: ClientConfiguration
Configurations for the WebSocket client. Following fields are inherited from the other configuration records in addition to the Client specific configs.
callbackService - Copied from CommonClientConfiguration |
subProtocols - Copied from CommonClientConfiguration |
customHeaders - Copied from CommonClientConfiguration |
idleTimeout - Copied from CommonClientConfiguration |
secureSocket - Copied from CommonClientConfiguration |
maxFrameSize - Copied from CommonClientConfiguration |
webSocketCompressionEnabled - Copied from CommonClientConfiguration |
handShakeTimeout - Copied from CommonClientConfiguration |
cookies - Copied from CommonClientConfiguration |
Fields
- Fields Included from * CommonClientConfiguration
- subProtocols string[]
- customHeaders map<string>
- readTimeout decimal
- secureSocket ClientSecureSocket
- maxFrameSize int
- webSocketCompressionEnabled boolean
- handShakeTimeout decimal
- cookies ballerina/http:1.1.0-alpha8:Cookie[]
- auth ballerina/websocket:1.2.0-alpha8:CredentialsConfig|ballerina/websocket:1.2.0-alpha8:BearerTokenConfig|ballerina/websocket:1.2.0-alpha8:JwtIssuerConfig|ballerina/websocket:1.2.0-alpha8:OAuth2ClientCredentialsGrantConfig|ballerina/websocket:1.2.0-alpha8:OAuth2PasswordGrantConfig|ballerina/websocket:1.2.0-alpha8:OAuth2RefreshTokenGrantConfig
- pingPongHandler PingPongService
websocket: ClientSecureSocket
Configures the SSL/TLS options to be used for WebSocket client.
Fields
- Fields Included from * ClientSecureSocket
- enable boolean
- cert ballerina/crypto:1.1.0-alpha8:TrustStore|string
- key ballerina/crypto:1.1.0-alpha8:KeyStore|ballerina/http:1.1.0-alpha8:CertKey
- protocol record {| ballerina/http:1.1.0-alpha8:Protocol name; string[] versions; |}
- certValidation record {| ballerina/http:1.1.0-alpha8:CertValidationType type; int cacheSize; int cacheValidityPeriod; |}
- ciphers string[]
- verifyHostName boolean
- shareSession boolean
- handshakeTimeout decimal
- sessionTimeout decimal
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. This is applicable only for the Sync client
- secureSocket ClientSecureSocket? - 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 ping/pong frames. Resources in this service gets called on the receipt of ping, pong from the server
websocket: CredentialsConfig
Represents credentials for Basic Auth authentication.
Fields
- Fields Included from * CredentialsConfig
websocket: JwtIssuerConfig
Represents JWT issuer configurations for JWT authentication.
Fields
- Fields Included from * IssuerConfig
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.
Fields
- Fields Included from * ListenerHttp1Settings
- keepAlive AUTO|ALWAYS|NEVER
- maxPipelinedRequests int
websocket: ListenerSecureSocket
Configures the SSL/TLS options to be used for WebSocket service.
Fields
- Fields Included from * ListenerSecureSocket
- key ballerina/crypto:1.1.0-alpha8:KeyStore|ballerina/http:1.1.0-alpha8:CertKey
- mutualSsl record {| ballerina/http:1.1.0-alpha8:VerifyClient verifyClient; ballerina/crypto:1.1.0-alpha8:TrustStore|string cert; |}
- protocol record {| ballerina/http:1.1.0-alpha8:Protocol name; string[] versions; |}
- certValidation record {| ballerina/http:1.1.0-alpha8:CertValidationType type; int cacheSize; int cacheValidityPeriod; |}
- ciphers string[]
- shareSession boolean
- handshakeTimeout decimal
- sessionTimeout decimal
websocket: OAuth2ClientCredentialsGrantConfig
Represents OAuth2 client credentials grant configurations for OAuth2 authentication.
Fields
- Fields Included from * ClientCredentialsGrantConfig
- tokenUrl string
- clientId string
- clientSecret string
- scopes string[]
- defaultTokenExpTime decimal
- clockSkew decimal
- optionalParams map<string>
- credentialBearer CredentialBearer
- clientConfig ClientConfiguration
websocket: OAuth2PasswordGrantConfig
Represents OAuth2 password grant configurations for OAuth2 authentication.
Fields
- Fields Included from * PasswordGrantConfig
- tokenUrl string
- username string
- password string
- clientId string
- clientSecret string
- scopes string[]
- refreshConfig record {| string refreshUrl; string[] scopes?; map<string> optionalParams?; ballerina/oauth2:1.1.0-alpha8:CredentialBearer credentialBearer; ballerina/oauth2:1.1.0-alpha8:ClientConfiguration clientConfig; |}
- defaultTokenExpTime decimal
- clockSkew decimal
- optionalParams map<string>
- credentialBearer CredentialBearer
- clientConfig ClientConfiguration
websocket: OAuth2RefreshTokenGrantConfig
Represents OAuth2 refresh token grant configurations for OAuth2 authentication.
Fields
- Fields Included from * RefreshTokenGrantConfig
- refreshUrl string
- refreshToken string
- clientId string
- clientSecret string
- scopes string[]
- defaultTokenExpTime decimal
- clockSkew decimal
- optionalParams map<string>
- credentialBearer CredentialBearer
- clientConfig ClientConfiguration
websocket: RequestLimitConfigs
Provides inbound request URI, total header and entity body size threshold configurations.
Fields
- Fields Included from * RequestLimitConfigs
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.
Constants
Annotations
websocket: ServiceConfig
The annotation which is used to configure a WebSocket service.
Types
websocket: ClientAuthConfig
Defines the authentication configurations for the WebSocket client.
websocket: OAuth2GrantConfig
Represents OAuth2 grant configurations for OAuth2 authentication.
Errors
websocket: Error
Represents any error related to the WebSocket module