WebSocket
API Reference: Net.WebSocket
WebSocket creates a websocket client. It is very simple to use. After you pass url parameter in constructor(this is mandatory) a websocket instance is created and onOpen callback triggers.

Reopen WebSocket

You can't send data after the websocket is closed. If you need, you must create a new web socket instance. Websocket isn't reopened automatically when send method calls if the websocket is closed.
TypeScript
1
import PageSampleDesign from 'generated/pages/pageSample';
2
import FlexLayout from '@smartface/native/ui/flexlayout';
3
import Application from '@smartface/native/application';
4
import WebSocket from '@smartface/native/net/websocket';
5
import Blob from '@smartface/native/global/blob';
6
7
//You should create new Page from UI-Editor and extend with it.
8
export default class Sample extends PageSampleDesign {
9
10
myWebSocket: WebSocket;
11
12
constructor() {
13
super();
14
// Overrides super.onShow method
15
this.onShow = onShow.bind(this, this.onShow.bind(this));
16
// Overrides super.onLoad method
17
this.onLoad = onLoad.bind(this, this.onLoad.bind(this));
18
19
this.layout.flexDirection = FlexLayout.FlexDirection.COLUMN;
20
this.layout.justifyContent = FlexLayout.JustifyContent.CENTER;
21
this.layout.alignItems = FlexLayout.AlignItems.CENTER;
22
}
23
}
24
25
/**
26
* @event onShow
27
* This event is called when a page appears on the screen (everytime).
28
* @param {function} superOnShow super onShow function
29
* @param {Object} parameters passed from Router.go function
30
*/
31
function onShow(superOnShow: () => void) {
32
const { headerBar } = this;
33
superOnShow();
34
Application.statusBar.visible = false;
35
headerBar.visible = false;
36
}
37
38
/**
39
* @event onLoad
40
* This event is called once when page is created.
41
* @param {function} superOnLoad super onLoad function
42
*/
43
function onLoad(superOnLoad: () => void) {
44
superOnLoad();
45
46
this.myWebSocket = new WebSocket({ url: "wss://echo.websocket.org" });
47
this.myWebSocket.onOpen = (): void => {
48
console.log("Web socket opened.");
49
console.log("Send string");
50
this.myWebSocket.send({ data: "some string" });
51
};
52
53
this.myWebSocket.close = (params: {code: number, reason?: string}) => {
54
console.log("onClose parameters : " + JSON.stringify(params));
55
};
56
57
this.myWebSocket.onMessage = (e: {string: string, blob: Blob}) => {
58
console.log("Message received.");
59
this.myWebSocket.close({ code: 1000 });
60
};
61
}
62
Copied!
Last modified 2mo ago
Copy link