Forked from ChrisZou/phoenix_channel_wechat_miniprogram_client_transport.js
Last active
July 23, 2018 17:00
-
-
Save sjava/f88a593afa062e2a5cce3a5103b26ff4 to your computer and use it in GitHub Desktop.
Phoenix Channel WeChat miniProgram client transport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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