Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ChrisZou/6b074fde3ebeafe43394bbeaee9e1bf3 to your computer and use it in GitHub Desktop.
Save ChrisZou/6b074fde3ebeafe43394bbeaee9e1bf3 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
}
send(encodedData) {
this.conn.send({ data: encodedData })
}
}
@sjava
Copy link

sjava commented Jul 24, 2018

hi,when run socket.conn.close(),but readyState not change ,allway SOCKET_STATES.open.close method change to

close(){this.conn.close()}

readyState can normal change.I'm newbie,is it OK?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment