Last active
July 24, 2018 02:04
-
-
Save ChrisZou/6b074fde3ebeafe43394bbeaee9e1bf3 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 | |
} | |
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
hi,when run socket.conn.close(),but readyState not change ,allway SOCKET_STATES.open.close method change to
readyState can normal change.I'm newbie,is it OK?