作者:哲學李論,來自原文地址
一、demo
socket.io在實時互動功能上是一個較為成熟的技術解決方案,有多種語言的實現(xiàn)。今天,我們使用兩個第三方類庫,一個client端,一個server端,在小程序中搭建一個簡單的聊天室。
簡單易用,是socket.io的基本特征。
1,下載https://github.com/wxsocketio/wxapp-socket-io
解壓,在weapp_demo目錄建立小程序項目。
2,安裝:go get github.com/googollee/go-socket.io
然后,使用我們寫好的server/main.go文件,運行:go run main.go
3,修改小程序項目app.js文件中的socket地址
-
const socket = io("ws://localhost:5000/socket.io/")
5000是在第2步指定的端口: http.ListenAndServe(":5000", nil)
/socket.io/是通過它指定的: http.Handle("/socket.io/", server)
可以下載我們打包的代碼:鏈接: https://pan.baidu.com/s/1c2vLIfA 密碼: asfb
二、說明
小程序index.js
-
socket.on('login', function(msg) {
-
wx.showToast({
-
title: '登錄成功\n用戶名:'+msg,
-
icon: 'success',
-
duration: 1000
-
})
-
-
setTimeout(
-
()=>{
-
wx.navigateTo({
-
url: '../room/index',
-
})
-
},
-
1000
-
)
socket.on("login"),代表監(jiān)聽來自server端的login事件,包括broadcast事情和emit事件。
broadcast和emit有什么區(qū)別?
前者是發(fā)給所有人(除了當前客戶端自己),emit是只回復給當前客戶端自己。
在main.go有: so.Emit("login", so.Id()) 這是發(fā)給小程序當前客戶端的。
附詳情說明: 服務器信息傳輸
-
// send to current request socket client
-
socket.emit('message', "this is a test");
-
// sending to all clients except sender
-
socket.broadcast.emit('message', "this is a test");
-
// sending to all clients in 'game' room(channel) except sender
-
socket.broadcast.to('game').emit('message', 'nice game');
-
// sending to all clients, include sender
-
io.sockets.emit('message', "this is a test");
-
// sending to all clients in 'game' room(channel), include sender
-
io.sockets.in('game').emit('message', 'cool game');
-
// sending to individual socketid
-
io.sockets.socket(socketid).emit('message', 'for your eyes only');
--
-
main.go:
-
so.Join("chat")
-
|