WebSocket
WebSocket is a network protocol that enables full-duplex communication over a single TCP connection. It simplifies data exchange between clients and servers and allows servers to push data proactively. With the WebSocket API, the browser and server only need to complete one handshake to establish a persistent, bidirectional connection.
Under normal conditions, each WebSocket goes through a series of states (lifecycle events):
- connecting: initial state. Messages may be queued and will not be transmitted until the socket opens.
- open: the socket is accepted by the remote peer and fully operational. Queued messages start transmitting immediately in either direction.
- closing: one side initiates a normal close. The socket continues to transmit queued messages, but rejects new messages.
- closed: all messages have been transmitted and all incoming messages have been received.
In abnormal situations (HTTP upgrade problems, connection issues, or abnormal close from either side), the WebSocket may enter the canceled state:
- canceled: the connection is broken. Messages queued on either side may not have been delivered.
Note that the state progression is independent on each side. Reaching a normal closed state means this side has sent all outgoing messages and received all incoming messages, but it does not guarantee the other peer has received all of its incoming messages.
In Auto.js Pro, you can create a WebSocket via $web.newWebSocket() and listen to the lifecycle events above.
let ws = $web.newWebSocket("wss://echo.websocket.org", {
eventThread: 'this'
});
ws.on("open", (res, ws) => {
log("WebSocket opened");
}).on("failure", (err, res, ws) => {
log("WebSocket connection failed or interrupted");
console.error(err);
}).on("closing", (code, reason, ws) => {
log("WebSocket closing");
}).on("closed", (code, reason, ws) => {
log("WebSocket closed: code = %d, reason = %s", code, reason);
});$web.newWebSocket(url[, options])
url{string} WebSocket URLoptions{object} Options (optional):eventThread{any} Thread used to dispatch WebSocket events. Default:ioio: events are fired on the WebSocket IO threadthis: events are fired on the thread that created the WebSocket. If that thread is blocked, events cannot be delivered in time.
Create and return a WebSocket instance. Use it to listen for lifecycle events or send text/binary messages.
WebSocket
Object returned by $web.newWebSocket.
Note: before Pro 9.0.10, WebSockets are not automatically closed/canceled when the script exits. For older versions, listen to the exit event and cancel manually. See WebSocket.cancel().
WebSocket.send(text)
text{string} Text message- Returns {boolean}
Enqueue text and send it as UTF-8 encoded text.
Returns true if the message is successfully enqueued. If the message buffer (16MB) is full, the message is rejected and a normal close is triggered (meaning queued messages will still be sent before closing). In that case, this method returns false.
Returns false if the socket is closed, closing, or canceled.
This method returns immediately and does not wait for the message to actually be sent.
let ws = $web.newWebSocket("wss://echo.websocket.org", {
eventThread: 'this'
});
ws.on("text", (text, ws) => {
console.info("Received text message: ", text);
});
console.log(ws.send('Hello, Auto.js Pro')); // returns true
ws.close(1000, null);
console.log(ws.send('GoodBye')); // returns falseWebSocket.send(bytes)
bytes{ByteString} Binary message- Returns {boolean}
Enqueue bytes and send it as binary data.
Returns true if the message is successfully enqueued. If the message buffer (16MB) is full, the message is rejected and a normal close is triggered (queued messages will still be sent before closing). In that case, this method returns false.
Returns false if the socket is closed, closing, or canceled.
This method returns immediately and does not wait for the message to actually be sent.
To create a binary message, use OkHttp’s API, for example:
let ByteString = Packages.okio.ByteString;
let ws = $web.newWebSocket("wss://echo.websocket.org", {
eventThread: 'this'
});
ws.on("text", (text, ws) => {
console.info("Received text message: ", text);
}).on("binary", (bytes, ws) => {
console.info("Received binary message: size ", bytes.size());
console.info("hex: ", bytes.hex());
console.info("base64: ", bytes.base64());
console.info("md5: ", bytes.md5());
console.info("bytes: ", bytes.toByteArray());
});
ws.send(ByteString.of($files.readBytes('./test.png'))); // create from byte[] and send
ws.send(ByteString.encodeUtf8('hello')); // UTF-8 encode string and send
ws.send(ByteString.decodeBase64('QXV0by5qcyBQcm8geXlkcw==')); // decode Base64 and send
ws.send(ByteString.decodeHex('621172314F60')); // decode hex and send
ws.close(1000, null);For more on ByteString, see ByteString.java
WebSocket.cancel()
Close resources held by the WebSocket immediately and drop the entire message queue. If the socket is already closed or canceled, nothing happens.
let ws = $web.newWebSocket("wss://echo.websocket.org", {
eventThread: 'this'
});
// Cancel WebSocket on script exit
events.on('exit', () => {
ws.cancel();
});WebSocket.close(code, reason)
code{number} Close status code. See RFC 6455 section 7.4. Common values include:- 1000: normal closure
- 1001: the endpoint is “going away”, e.g. server shutting down or browser navigating away
- 1002: protocol error
- 1003: unsupported data type
- ...
reason{string} Close reason (UTF-8, at most 123 bytes), ornull- Returns {boolean}
Attempt to normally close the WebSocket. After calling this method, all subsequent send calls will be rejected and return false (no new messages are accepted), but messages already in the queue will continue to be transmitted.
Throws IllegalArgumentException if code is out of range or reason is too long.
Returns false if the socket is closing/closed/canceled; otherwise returns true.
let ws = $web.newWebSocket("wss://echo.websocket.org", {
eventThread: 'this'
});
setTimeout(() => {
ws.close(1000, null);
}, 5000);