小程序模板網(wǎng)

小程序即時通訊demo

發(fā)布時間:2018-10-11 09:44 所屬欄目:小程序開發(fā)教程

前段時間寫了一個小程序即時聊天demo,仿微信,效果如下:

 

大家可以自行下載,按照提示運行,就能看到效果;現(xiàn)在只是做了要給基本版的,要做復(fù)雜功能,可以繼續(xù)添加。

功能

  1. 發(fā)送文字
  2. 發(fā)送圖片(圖片可點擊放大)
  3. 發(fā)送拍攝照片 (圖片可點擊放大)
  4. 發(fā)送位置 (map組件默認在最頂層,樣式控制不了,bug還在修復(fù)中...)
  5. 發(fā)送語音 (包括語音時長,可點擊播放)

websorket長連接

是基于nodejs-websocket的服務(wù),代碼如下:(最基礎(chǔ)版)


var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
//創(chuàng)建一個server
var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("text", function (str) { 
		// console.log("Received "+str)
		// conn.sendText(str.toUpperCase()+"!!!")
		//鏈接成功之后,發(fā)送歡迎語
		console.log("連接成功")
		//歡迎語
		if(str == 'null'){
			conn.sendText("有什么能幫到您?");
		}
		//輸入文字
		else if(str != 'null' && str){
			conn.sendText("文字")
		}
		//輸入多媒體
		else{
			conn.sendText("多媒體文本")
		}
		console.log(str);
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
	})
}).listen(8001)
復(fù)制代碼

在項目根目錄下運行 npm run dev 服務(wù)就能啟動了, 啟動之后websorket地址為: ws://localhost:8001

chat.js

直接看代碼,注釋都寫清楚了

<a data-cke-saved-href="http://www.yiyongtong.com/uploads/allimg/181011/09444H039-0.gif" href="http://www.yiyongtong.com/uploads/allimg/181011/09444H039-0.gif" target="_blank">
// pages/user/chat.js
var util = require('../utils/util.js');
var app = getApp();
//websocket心跳重連對象
let heartCheck = {
  timeout: 1000,//1s
  timeoutObj: null,
  serverTimeoutObj: null,
  //重置
  reset: function () {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  //開始
  start: function () {
    wx.sendSocketMessage({
      data: "null",
    });
  }, 
}; 
//微信小程序新錄音接口,錄出來的是aac或者mp3,這里要錄成mp3
const recorderManager = wx.getRecorderManager();
const options = {
  duration: 600000,//錄音時長,這里設(shè)置的是最大值10分鐘
  sampleRate: 44100,
  numberOfChannels: 1,
  encodeBitRate: 192000,
  format: 'mp3',
  //frameSize: 50 
};

//音頻播放
const innerAudioContext = wx.createInnerAudioContext()

Page({ 
  data: {  
    taskId:'',
    userId:'',
    chatList:[],//聊天內(nèi)容
    isShowModelUp:false,//底部彈框顯示true,隱藏為false 
    isLuYin:false,//沒有錄音false,開始錄音true
    luYinText:'按住說話',
    audioUrl:'',//錄音文件地址
    isShowLuYin:false,//true為開始播放,false為取消播放
    inputValue:'',//輸入框內(nèi)容
    lockReconnect:false,//默認進來是斷開鏈接的
    limit:0,//重連次數(shù)
  }, 
  onLoad: function (options) { 
    this.linkSocket(); 
  }, 
  //連接socket
  linkSocket:function(){
    let that = this;
    wx.connectSocket({
      //url: app.globalData.wsUrl + 'websocket?' + this.data.taskId + '&' + this.data.userId,
      url:app.globalData.wsUrl,
      success() {
        console.log('連接成功')
        wx.onSocketMessage((res) => {
          console.log(res.data);
          //收到消息
          that.pushChatList(0, {
            text: res.data
          });
        })
        wx.onSocketOpen(() => {
          console.log('WebSocket連接打開')
          heartCheck.reset().start()
        })
        wx.onSocketError(function (res) {
          console.log('WebSocket連接打開失敗')
          that.reconnect()
        })
        wx.onSocketClose(function (res) {
          console.log('WebSocket已關(guān)閉!')
          that.reconnect()
        })
      }
    }) 
  }, 
  //斷線重連
  reconnect() { 
    var that = this;
    if (that.lockReconnect) return;
    that.lockReconnect = true;
    clearTimeout(that.timer)
    if (that.data.limit < 12) {
      that.timer = setTimeout(() => {
        that.linkSocket();
        that.lockReconnect = false;
      }, 5000);
      that.setData({
        limit: that.data.limit + 1
      })
    } 
  }, 
  //打開底部彈框
  showModelUp:function(){ 
    var that=this; 
    if (that.data.isShowModelUp==false){
      that.setData({
        isShowModelUp: true, 
      })
    }else{
      that.setData({
        isShowModelUp: false, 
      })
    } 
  },
  //關(guān)閉底部彈框
  closeModelUp:function(){
    var that=this;
    that.setData({
      isShowModelUp:false, 
    })
  },
  //選擇照片
  chooseImage:function(){
    var that=this;
    wx.chooseImage({ 
      count: 1, // 默認9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: ['album'], // 可以指定來源是相冊還是相機,默認二者都有
      success: function (res) { 
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths;
        console.log(res);
        that.pushChatList(1,{
          imgUrl: tempFilePaths,
        }) 
        //關(guān)閉彈窗
        that.closeModelUp();
        that.pageScrollToBottom();
      }
    })
  },
  //界面滾到最底端
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#bottom').boundingClientRect(function (rect) {
      console.log(rect.top);
      console.log(rect.bottom);
      // 使頁面滾動到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom + 200
      })
    }).exec()
  },
  //預(yù)覽圖片
  previewImage:function(e){
    console.log(e);
    var url=e.currentTarget.dataset.src;
    var that=this;
    wx.previewImage({
      current: url[0], // 當前顯示圖片的http鏈接
      urls: url // 需要預(yù)覽的圖片http鏈接列表
    })
  },
  //拍攝
  paishe:function(){
    var that = this;
    wx.chooseImage({
      count: 1, // 默認9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: ['camera'], // 可以指定來源是相冊還是相機,默認二者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths;
        console.log(res);
        that.pushChatList(1,{
          imgUrl: tempFilePaths,
        })
        //關(guān)閉彈窗
        that.closeModelUp();
        that.pageScrollToBottom();
      }
    })
  },
  //發(fā)送位置
  getlocat: function () {
    var that = this
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的經(jīng)緯度
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: [{
            latitude: res.latitude,
            longitude: res.longitude,
            name: '時代一號',
            desc: '現(xiàn)在的位置'
          }], 
        })
        that.pushChatList(1,{
          map: true
        })
      }
    })
    that.closeModelUp();
    that.pageScrollToBottom();
  },
  //切換是否錄音按鈕
  btnRecord:function(){ 
    var that=this;
    if (that.data.isLuYin==false){
      that.setData({
        isLuYin: true
      });
    }else{
      that.setData({
        isLuYin: false,
        luYinText: '按住說話'
      });
    }  
  },
  //開始錄音
  startRecord:function(e){ 
    var that=this;
    that.setData({
      luYinText:'錄音中...', 
    }); 
    recorderManager.start(options); 
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
  },
  //結(jié)束錄音
  stopRecord:function(){ 
    var that = this;
    that.setData({
      luYinText: '按住說話'
    });
    recorderManager.stop();  
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res;
      that.pushChatList(1,{
        audioUrl: res.tempFilePath,
        audioDuration: (res.duration / 60000).toFixed(2),//錄音時長,轉(zhuǎn)為分,向后取兩位,
      })
      that.setData({
        audioUrl: res.tempFilePath,
        audioDuration: (res.duration / 60000).toFixed(2),//錄音時長,轉(zhuǎn)為分,向后取兩位,
      })
    })
    //關(guān)閉彈窗
    that.closeModelUp();
    that.pageScrollToBottom();
  },
  //錄音、停止播放
  playRecord:function(e){  
    console.log(e);
    var that=this;  
    innerAudioContext.autoplay = true;
    innerAudioContext.src = that.data.audioUrl
    //innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46';//測試音頻文件
    if (!e.currentTarget.dataset.isshowluyin){//開始播放 
      //innerAudioContext.play();//兼容起見用它
      innerAudioContext.onPlay(() => {
        console.log('開始播放');
        that.setData({ 
          isShowLuYin: true
        }); 
        return;
      }); 
    }else{//暫停播放 
      innerAudioContext.pause();
      console.log("暫停");
      that.setData({
        isShowLuYin: false
      });
      return; 
    } 
  },
  //輸入框點擊完成按鈕時觸發(fā)
  btnConfirm:function(e){
    var that = this;
    if (typeof (e) == 'undefined' || e.detail.value == ''){
      return false;
    }else {  
      var value = e.detail.value;
      that.pushChatList(1,{
        text: value
      });
      that.setData({
        inputValue:''//清空輸入框
      })
      //發(fā)送數(shù)據(jù)
      wx.sendSocketMessage({
        data: value
      })
      //關(guān)閉彈窗
      that.closeModelUp();
      that.pageScrollToBottom();
    }
  },
  //頁面隱藏/切入后臺時觸發(fā)
  onHide:function(){
    wx.onSocketClose(function (res) {
      console.log('WebSocket已關(guān)閉!') 
    })
  },
  //頁面卸載時觸發(fā)
  onUnload:function(){
    wx.onSocketClose(function (res) {
      console.log('WebSocket已關(guān)閉!')
    })
  },

</a>

 


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://22321a.com/wxmini/doc/course/24854.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點擊咨詢
QQ在線咨詢