小程序直播聊天
//在页面最上面定义全局变量,脚本中使用。var socketOpen = falsevar SocketTask, url//打开页面的时候执行webSocketonLoad () { url = "wss://www.xlroader.com/wss/" + id},onShow () { if (!socketOpen) { this.webSocket() }}webSocket () { // 创建Socket SocketTask = wx.connectSocket({ url: url, method: 'post', success: function(res) { console.log('WebSocket连接创建', res) } }) // 监听Socket打开 SocketTask.onOpen(res => { socketOpen = true console.log('监听 WebSocket 连接打开事件。', res) }) // 监听Socket发送消息 SocketTask.onMessage(res => { console.log('发送了一条消息') res.data = JSON.parse(res.data) console.log(res.data) res = res.data if (res.msgtype == "msgcontent" && res.actid == this.data.id) { //chatArr是聊天数据的数组,包含用户昵称和用户发送的文本信息 this.data.chatArr.push({ name: res.name, text: res.text }) this.setData({ chatArr: this.data.chatArr, //每次输入内容之后更改scrollTop的值,让它滑动到最底端 scrollTop: this.data.chatArr.length * 100 }) } }) // 监听Socket关闭 SocketTask.onClose(res => { console.log('关闭 WebSocket 连接。') socketOpen = false })}//websocket创建完毕之后,就可以愉快的发送消息了,代码如下:// 发送消息onInputTap(event) { let value = event.detail.value let name = app.globalData.userInfo.nickName let data = { name: name, text: value } // 如果webSocket创建 if (socketOpen) { // 将发消息人的昵称和内容发送出去 this.sendSocketMessage(data) this.data.chatArr.push({ name: name, text: value }) this.setData({ scrollTop: this.data.chatArr.length * 100, inputValue: "", chatArr: this.data.chatArr }) }},// 发送数据sendSocketMessage(msg) { msg.id = this.data.id, msg.memberid = app.globalData.memberid SocketTask.send({ data: JSON.stringify(msg) }, (res) => { console.log(res) })}//如果关闭页面或者关闭微信// 页面关闭onUnload() { SocketTask.close({ reason: this.data.id })},// 页面卸载onHide() { SocketTask.close({ reason: this.data.id })}/*基本的聊天模块就以上代码,然后在使直播全屏化的过程中,又发现了一个小问题,那就是直播全屏之后不是铺满屏幕的,而只占了中间一小块,后来查了下,原来是需要设置画面的方向,官方提供了orientation这个属性,orientation: "horizontal"即可设置全屏,代码如下:*/// 全屏fullScreen() { let that = this let fullScreenFlag = that.data.fullScreenFlag if (fullScreenFlag) { fullScreenFlag = false } else { fullScreenFlag = true } if (fullScreenFlag) { //全屏 that.PlayerCtx.requestFullScreen({ success: res => { that.setData({ fullScreenFlag: fullScreenFlag, liveDirection: "horizontal" }); } } else { //缩小 that.PlayerCtx.exitFullScreen({ success: res => { that.setData({ fullScreenFlag: fullScreenFlag, liveDirection: "vertical" }); } } },小程序
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

