WebSocket with Pusher: Disconnect after 10 seconds
Using the websocket.js example I made a connection with Pusher, but it is not being maintained after 10 seconds
In my code I have connection.connect('close', () => log('closed')
, but this is not executed when the connection is closed
My code:
const { GLib, Soup } = imports.gi
const byteArray = imports.byteArray
// my app key
const MY_KEY = ''
const CLUSTER = ''
// URL -> https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol/
const url =
'ws://ws-' +
CLUSTER +
'.pusher.com/app/' +
MY_KEY +
'?client=gjs-libpushergjs&protocol=7&version=1.0'
// asynchronous
const loop = GLib.MainLoop.new(null, false)
async function main() {
const connection = await createConnection()
connection.connect('closed', () => log('closed')) // print if closed connection
connection.connect('error', () => log('error')) // print if exists error on connection
connection.connect('message', (self, type, data) => {
data = parseData(data) // return json (public channels)
log(JSON.stringify(data))
})
}
main().catch(e => logError(e))
function createConnection() {
return new Promise((resolve, reject) => {
const session = new Soup.Session()
const message = new Soup.Message({ method: 'GET', uri: Soup.URI.new(url) })
session.websocket_connect_async(
message,
'Gnome Shell - libpushergjs',
['ws'],
null,
(_session, res) => {
try {
// connection with Pusher
resolve(session.websocket_connect_finish(res))
} catch (e) {
reject(e)
}
}
)
})
}
function parseData(data) {
const dataString = byteArray.toString(byteArray.fromGBytes(data))
return JSON.parse(dataString)
}
loop.run()