# WebSockets

Management of WebSockets.

# Manifest Declaration

You need to declare the use of this API in the manifest's features member:

{"name": "system.websocketfactory"}

# Module Import

Before using this service in a component, you need to import the module in the script section of the UX document.

import websocketfactory from '@system.websocketfactory' 

Or

let websocketfactory = require("@system.websocketfactory")

# Methods

This service has the following methods:

# create({url,header,protocols})

Creates a WebSocket connection.

Every time this method is called, a new object is created. The number is not limited.

Timeout configuration

You can configure the network timeout in the config.network member of the manifest.

# Arguments

This method requires an object with the following attributes:

  • url (string). Mandatory attribute with the URL of the WebSocket server (i.e., wss:// or ws://).
  • header (object). Optional attribute with the HTTP header (it cannot contain Referer).
  • protocols (array). Optional attribute with the protocols to be used.

Example:

var websocket = websocketfactory.create({ 
    url: 'ws://echo.websocket.org', 
    header:{ 
        'content-type': 'application/json' 
    }, 
    protocols: ['protocol1'] 
})

# send({data,success,fail})

This method uses a existing WebSocket object to deliver a message.

# Arguments

This method requires an object with the following attributes:

  • data (string|ArrayBuffer). Mandatory attribute with the data to be sent. The data size cannot exceed 16 MB.
  • header (object). Optional attribute with the HTTP header (it cannot contain Referer).
  • protocols (array). Optional attribute with the protocols to be used.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function). Optional callback function corresponding to the failed execution.

Example:

websocket.send({ 
    data: 'Text message', 
    success:function() { 
        console.log('success'); 
    }, 
    fail:function() { 
        console.log('failed'); 
    } 
})

var buffer = new ArrayBuffer(4); 
var a = new Uint8Array(buffer); 
a[0] = 1; 
a[1] = 2; 
a[2] = 3; 
a[3] = 4; 
websocket.send({ 
    data: buffer, 
    success: function () { 
        console.log('success'); 
    }, 
    fail: function () { 
        console.log('failed'); 
    } 
}) 

# close({code,reason,success,fail})

This method closes a existing WebSocket object.

# Arguments

This method requires an object with the following attributes:

  • code (number). Optional attribute with a code with the status of closed connection (1000 by default).
  • reason (string). Optional attribute with a text with the reason for closing a connection.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function). Optional callback function corresponding to the failed execution.

Example:

websocket.close({ 
    code: 1000, 
    reason: 'closing normally', 
    success: function() { 
        console.log('close success'); 
    }, 
    fail: function() { 
        console.log('close fail'); 
    } 
})

# Events

This service provides the following listeners:

# onopen(function)

Listener for WebSocket connections.

# Arguments

This method requires a function that will be run when the connection is opened.

Example:

websocket.onopen = function() { 
    console.log('connect open'); 
}

# onmessage(function({data}))

Listener of WebSocket connections triggered when a message is received.

# Arguments

This method may include a callback function as a parameter that has an object argument with the following member:

  • data (string|ArrayBuffer) with the message data received by the listener.

Example:

websocket.onmessage = function (e) { 
    console.log("onmessage e = "+e.data); 
} 
websocket.onmessage = function (e) { 
    console.log("onmessage e = "+JSON.stringify(String.fromCharCode.apply(null, new Uint8Array(e.data)))); 
}

# onclose(function({code,reason,wasClean}))

Listener of WebSocket connection when it's closed.

# Arguments

This method may include a callback function as a parameter that has an object argument with the following members:

  • code (number) with the number of the code indicating the status returned by the server.
  • reason (string) with the textual description of the reason for closing the connection, returned by the server.
  • wasClean (boolean). A flag that indicates if a connection is completely closed.

The possible status codes are:

Code Description
1000 The connection is closed normally
1001 Going Away
1002 Protocol error
1003 Unsupported data
1005 No status received
1006 The connection is closed
1007 Invalid frame payload data
1008 Policy Violation
1009 The message is too large
1010 Missing extension
1011 Internal Error
1012 Service Restart
1013 Try again later
1014 Bad gateway
1015 TLS handshake

Example:

websocket.onclose = function(e) { 
    console.log("onclose e.code = "+e.code+", e.reason = "+e.reason+", wasClean = "+e.wasClean); 
}

# onerror(function({data}))

Listener of WebSocket connection when an error happens.

# Arguments

This method may include a callback function as a parameter that has an object argument with the following member:

  • data (string) with the message data received by the listener.

Example:

websocket.onerror = function(e) { 
    console.log("onerror e.data = "+e.data); 
}

# Example

<template> 
    <div> 
        <div> 
            <text>WebSocket Example</text> 
        </div> 
        <div> 
            <text>Connect to the specified URL: {{isSuccess}}</text> 
        </div> 
        <input type="button" onclick="connectWebsocket" value="Connect to the specified URL." /> 
        <div> 
            <text>Connect to the specified URL 2: {{isSuccess2}}</text> 
        </div> 
        <input type="button" onclick="connectWebsocket2" value="Connect to the specified URL 2." /> 
        <div> 
            <text>Connect to the specified URL 3: {{isSuccess3}}</text> 
        </div> 
        <input type="button" onclick="connectWebsocket3" value="Connect to the specified URL 3." /> 
        <div> 
            <text>Send a message: {{isSend}}</text> 
        </div> 
        <input type="button" onclick="sendMessage" value="Send a message." /> 
        <input type="button" onclick="closeWebsocket" value="Close" /> 
        <div> 
            <text>Send a message: {{isSend2}}</text> 
        </div> 
         <input type="button" onclick="sendMessage2" value="Send message 2." /> 
        <input type="button" onclick="closeWebsocket2" value="Close 2" /> 
        <div> 
            <text>Send a message: {{isSend3}}</text> 
        </div> 
        <input type="button" onclick="sendMessage3" value="Send message 3." /> 
        <input type="button" onclick="closeWebsocket3" value="Close 3" /> 
    </div> 
</template> 
<style> 
    .item-container { 
        margin-bottom: 50px; 
        margin-right: 60px; 
        margin-left: 60px; 
        flex-direction: column; 
    } 
    .item-content { 
        flex-direction: column; 
        background-color: #ffffff; 
        padding-left: 30px; 
        padding-right: 30px; 
        padding-top: 20px; 
        padding-bottom: 20px; 
        margin-bottom: 30px; 
        align-items: flex-start; 
    } 
    .txt { 
        padding-top: 15px; 
        padding-bottom: 15px; 
    } 
</style> 
<script> 
    import websocketfactory from '@system.websocketfactory' 
    export default { 
        data: { 
            isSuccess: '', 
            isSend: '', 
            isSend2: '', 
            isSend3: '', 
            websocket: '', 
            isSuccess2: '', 
            isSuccess3: '', 
            websocket2: '', 
        }, 
        onInit: function () { 
            this.$page.setTitleBar({ text: 'Websocket' }) 
        }, 
        connectWebsocket: function () { 
            var self = this; 
            self.websocket = websocketfactory.create({ 
                url: 'ws://echo.websocket.org' 
            }) 
            self.websocket.onmessage = function (e) { 
                console.log("onmessage e = " + e.data); 
            } 
            self.websocket.onclose = function (e) { 
                console.log("onclose e.code = " + e.code + ", e.reason = " + e.reason + ", wasClean = " + e.wasClean); 
            } 
            self.websocket.onerror = function (e) { 
                console.log("onerror e.data = " + e.data); 
                self.isSuccess = "Connection failed."; 
            } 
            self.websocket.onopen = function () { 
                console.log('connect open'); 
                self.isSuccess = "Connection successful."; 
            } 
        }, 
        sendMessage: function () { 
            var self = this; 
            if (self.websocket) { 
                self.websocket.send({ 
                    data: 'send message', 
                    success: function () { 
                        console.log(' success'); 
                        self.isSend = "Sending successful."; 
                    }, 
                    fail: function () { 
                        console.log('failed'); 
                        self.isSend = "Sending failed."; 
                    } 
                }) 
            } 
        }, 
        closeWebsocket: function () { 
            var self = this; 
            if (self.websocket) { 
                self.websocket.close({ 
                    code: 1000, 
                    reason: 'close as normal', 
                    success: function () { 
                        console.log('close success!!!'); 
                    }, 
                    fail: function () { 
                        console.log('close fail'); 
                    } 
                }) 
            } 
        }, 
        connectWebsocket2: function () { 
            var self = this; 
            self.websocket2 = websocketfactory.create({ 
                url: 'ws://echo.websocket.org', 
                header: { 
                    'content-type': 'application/json' 
                }, 
                protocols: ['protocol1'] 
            }) 
            self.websocket2.onmessage = function (e) { 
                console.log("2 onmessage e = " + e.data); 
            } 
            self.websocket2.onclose = function (e) { 
                console.log("2 onclose e.code = " + e.code + ", e.reason = " + e.reason); 
            } 
            self.websocket2.onerror = function (e) { 
                console.log("2 onerror e.data = " + e.data); 
                self.isSuccess2 = "Connection failed."; 
            } 
            self.websocket2.onopen = function () { 
                console.log('2 connect open'); 
                self.isSuccess2 = "Connection successful."; 
            } 
        }, 
        sendMessage2: function () { 
            var self = this; 
            if (self.websocket2) { 
                self.websocket2.send({ 
                    data: 'send2 message', 
                    success: function () { 
                        console.log('success2'); 
                        self.isSend2 = "Sending successful."; 
                    }, 
                    fail: function () { 
                        console.log('failed 2'); 
                        self.isSend2 = "Sending failed."; 
                    } 
                }) 
            } 
        }, 
        closeWebsocket2: function () { 
            var self = this; 
            if (self.websocket2) { 
                self.websocket2.close({ 
                    code: 1000, 
                    reason: 'close as normal', 
                    success: function () { 
                        console.log('close2 success!!!'); 
                    }, 
                    fail: function () { 
                        console.log('close2 fail'); 
                    } 
                }) 
            } 
        }, 
        connectWebsocket3: function () { 
            var self = this; 
            self.websocket3 = websocketfactory.create({ 
                url: 'ws://echo.websocket.org', 
                header: { 
                    'content-type': 'application/json' 
                }, 
                protocols: ['protocol1'] 
            }) 
            self.websocket3.onmessage = function (e) { 
                console.log("3 onmessage e = " + JSON.stringify(String.fromCharCode.apply(null, new Uint8Array(e.data)))); 
            } 
            self.websocket3.onclose = function (e) { 
                console.log("3 onclose e.code = " + e.code + ", e.reason = " + e.reason); 
            } 
            self.websocket3.onerror = function (e) { 
                console.log("3 onerror e.data = " + e.data); 
                self.isSuccess3 = "Connection failed."; 
            } 
            self.websocket3.onopen = function () { 
                console.log('3 connect open'); 
                self.isSuccess3 = "Connection successful."; 
            } 
        }, 
        sendMessage3: function () { 
            var self = this; 
            var buffer = new ArrayBuffer(4); 
            var a = new Uint8Array(buffer); 
            a[0] = 1; 
            a[1] = 2; 
            a[2] = 3; 
            a[3] = 4; 
            if (self.websocket3) { 
                self.websocket3.send({ 
                    data: buffer, 
                    success: function () { 
                        console.log('success3'); 
                        self.isSend3 = "Sending successful."; 
                    }, 
                    fail: function () { 
                        console.log('failed 3'); 
                        self.isSend3 = "Sending failed."; 
                    } 
                }) 
            } 
        }, 
        closeWebsocket3: function () { 
            var self = this; 
            if (self.websocket3) { 
                self.websocket3.close({ 
                    code: 1000, 
                    reason: 'close as normal', 
                    success: function () { 
                        console.log('close3 success!!!'); 
                    }, 
                    fail: function () { 
                        console.log('close3 fail'); 
                    } 
                }) 
            } 
        } 
    } 
</script>