Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sjava/f88a593afa062e2a5cce3a5103b26ff4 to your computer and use it in GitHub Desktop.
Save sjava/f88a593afa062e2a5cce3a5103b26ff4 to your computer and use it in GitHub Desktop.
Phoenix Channel WeChat miniProgram client transport
//This is a WeChat miniprogram client transport for phoenix.js
// so that you can use easily use Phoenix Channel as a WebSocket server.
// Written by @chrismccord
// example usage:
// ```
// let socket = new Socket("ws://localhost:4000/socket", { transport: WxSocket })
// socket.connect()
// let channel = socket.channel("room:lobby", {})
// channel.join()
// .receive("ok", resp => { console.log("Joined successfully", resp) })
// .receive("error", resp => { console.log("Unable to join", resp) })
//
// channel.push("new_msg", {body: "Hello from miniprogram!"})
// ```
class WxSocket {
constructor(url) {
// Create the underlying connection, which in this case is a SocketTask
this.conn = wx.connectSocket({ url: url })
const SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 }
this.readyState = SOCKET_STATES.connecting
this.onopen = function () { }
this.onerror = function () { }
this.onmessage = function () { }
this.onclose = function () { }
this.conn.onOpen(() => {
this.readyState = SOCKET_STATES.open
this.onopen()
})
this.conn.onError(error => {
this.readyState = SOCKET_STATES.closed
this.onerror(error)
})
this.conn.onMessage(event => {
this.onmessage(event)
})
this.conn.onClose(event => {
this.readyState = SOCKET_STATES.closed
this.onclose(event)
})
// this.close = this.conn.close
}
close() {
this.conn.close()
}
send(encodedData) {
this.conn.send({ data: encodedData })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment