欢迎光临,了解微信小程序开发,就上易用通!

使用socket.io搭建简单聊天室

发布:2018-04-16 11:53浏览: 来源:网络 作者:cola

作者:哲学李论,来自原文地址

一、demo

socket.io在实时互动功能上是一个较为成熟的技术解决方案,有多种语言的实现。今天,我们使用两个第三方类库,一个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地址

 

					
  1. 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

 

					
  1. socket.on('login', function(msg) {
  2. wx.showToast({
  3. title: '登录成功\n用户名:'+msg,
  4. icon: 'success',
  5. duration: 1000
  6. })
  7.  
  8. setTimeout(
  9. ()=>{
  10. wx.navigateTo({
  11. url: '../room/index',
  12. })
  13. },
  14. 1000
  15. )

socket.on("login"),代表监听来自server端的login事件,包括broadcast事情和emit事件。

broadcast和emit有什么区别?

前者是发给所有人(除了当前客户端自己),emit是只回复给当前客户端自己。

在main.go有:  so.Emit("login", so.Id())  这是发给小程序当前客户端的。

附详情说明:  服务器信息传输

 

					
  1. // send to current request socket client
  2. socket.emit('message', "this is a test");
  3. // sending to all clients except sender
  4. socket.broadcast.emit('message', "this is a test");
  5. // sending to all clients in 'game' room(channel) except sender
  6. socket.broadcast.to('game').emit('message', 'nice game');
  7. // sending to all clients, include sender
  8. io.sockets.emit('message', "this is a test");
  9. // sending to all clients in 'game' room(channel), include sender
  10. io.sockets.in('game').emit('message', 'cool game');
  11. // sending to individual socketid
  12. io.sockets.socket(socketid).emit('message', 'for your eyes only');

--

 

					
  1. main.go:
  2. so.Join("chat")
  3.  





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。