WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's H5/iOS/android and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply
::: warning iOS and h5 provide webSocket default handle. if you use webSocket in android environment. You should provide custom adapter implementation, source:
create websocket
const ws = weex.requireModule('webSocket'); ws.WebSocket('ws://echo.websocket.org','');
Transmits data to the server over the WebSocket connection
const ws = weex.requireModule('webSocket'); ws.WebSocket('ws://echo.websocket.org',''); ws.send('some message.');
Closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
const ws = weex.requireModule('webSocket'); ws.WebSocket('ws://echo.websocket.org',''); ws.close();
An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data.
const ws = weex.requireModule('webSocket') ws.WebSocket('ws://echo.websocket.org',''); ws.onopen = function(event) { console.log('onopen', event); }
An event listener to be called when a message is received from the server
data
, string, the listener received message.const ws = weex.requireModule('webSocket') ws.WebSocket('ws://echo.websocket.org',''); ws.onmessage = function(event) { console.log('onmessage', event); }
An event listener to be called when the WebSocket connection's readyState changes to CLOSED
code
, number, returns an unsigned short containing the close code send by the server.reason
, string, returns a string indicating the reason the server closed the connection.wasClean
, boolen, returns a Boolean that Indicates whether or not the connection was cleanly closed.const ws = weex.requireModule('webSocket') ws.WebSocket('ws://echo.websocket.org',''); ws.onclose = function(event) { console.log('onclose', event); }
An event listener to be called when an error occurs.
data
, string, the listener received error data.const ws = weex.requireModule('webSocket') ws.WebSocket('ws://echo.websocket.org',''); ws.onerror = function(event) { console.log('onerror', event); }
Demos