• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

微信小程序实现即时通信聊天功能的实例代码

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

项目背景:小程序中实现实时聊天功能

一、服务器域名配置

配置流程

配置参考URL:https://developers.weixin.qq.com/miniprogram/dev/api/api-network.html

二、nginx中配置反向代理加密websocket(wss)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
upstream websocket{
 hash $remote_addr consistent;
 server 127.0.0.1:9090 weight=5 max_fails=3 fail_timeout=30s;
}
server {
 listen 80;
 server_name www.xxxx.cn;
 rewrite ^(.*)$ https://$host$1 permanent;
}
server
 {
 listen 443;
  server_name www.xxxx.cn;
  ssl on;
  root /home/wwwroot/yzcp;
  index index.php index.html index.htm;
  ssl_certificate /usr/local/nginx/conf/cert/1526060965511.pem;#这里是服务端证书路径
  ssl_certificate_key /usr/local/nginx/conf/cert/1526060965511.key;#这里是密钥路径
  ssl_session_timeout 5m;
  ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  ssl_verify_client off;
 #隐藏index.php
  location / {
 #index index.php;
 deny 127.0.0.1;
   if (!-e $request_filename) {
    #一级目录
    rewrite ^(.*)$ /index.php?s=$1 last;
    break;
   }
   #wss配置
   client_max_body_size 100m;
   proxy_redirect off;
   proxy_pass http://websocket;#反向代理转发地址
   proxy_set_header Host $host;# http请求的主机域名
   proxy_set_header X-Real-IP $remote_addr;# 远程真实IP地址
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#反向代理之后转发之前的IP地址
   proxy_read_timeout 604800s;#websocket心跳时间,默认是60s
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "Upgrade";
  }
  location ~ .+\.php {
   fastcgi_pass unix:/tmp/php-cgi.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   set $path_info "";
   set $real_script_name $fastcgi_script_name;
    if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
    set $real_script_name $1;
    set $path_info $2;
   }
   fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
   fastcgi_param SCRIPT_NAME $real_script_name;
   fastcgi_param PATH_INFO $path_info;
  }
  
  #防盗链开始
  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
 {
 expires  30d;
 }
 location ~ .*\.(js|css)?$
 {
 expires  12h;
 }
 access_log /home/wwwlogs/www1537ucn.log;
 }

三、安装swoole

编译安装:

1
2
3
4
5
6
7
8
9
10
wget http://pecl.php.net/get/swoole-1.9.3.tgz  //下载swoole
tar -zvxf swoole-1.9.3.tgz  //解压swoole
cd swoole-1.9.3/;  //进入swoole
/usr/local/php54/bin/phpize;  //生成configure
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install   //安装
cd /phpstudy/server/php/lib/php/extensions/no-debug-non-zts-20121212 //查看是否安转上了swoole.so (注意:此文件下边都是你安装的拓展)
vim /phpstudy/server/php/etc/php.ini  //在php.ini添加extension=swoole.so加入到文件最后一行
lnmp restart; //重启nginx
php -m; //查看phpinfo,这时候swoole拓展已经装上了

四、服务器端运行程序

1、创建server.php放到项目的根目录即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
//实例化一个swoole的websocket服务监听本机的9501端口
$server = new swoole_websocket_server("服务器IP", 9090);
//只需要绑定要监听的ip和端口。如果ip指定为127.0.0.1,则表示客户端只能位于本机才能连接,其他计算机无法连接。
//端口这里指定为9090,可以通过netstat查看下该端口是否被占用。如果该端口被占用,可更改为其他端口,如9502,9503等。
$server->on(\'open\', function (swoole_websocket_server $server, $request) {
 echo "你好连接成功{$request->fd}\n";
});
$server->on(\'message\', function (swoole_websocket_server $server, $frame) {
 foreach($server->connections as $key => $fd) {
  $user_message = $frame->data;
  $server->push($fd, $user_message);
 }
});
$server->on(\'close\', function ($ser, $fd) {
 echo "client {$fd} closed\n";
});
$server->start();
?>

2、由于swoole_server只能运行在CLI模式下,所以不要试图通过浏览器进行访问,这样是无效的,我们在命令行下面执行,注意一定要找到php的绝对路径php  server.php  (这行代码的意思是,把程序在服务器跑起来)

注意:php server.php命令运行后,下面的黑框关闭后将无法聊天。所以一般使用命令:nohup php server.php &

五、客户端

1、网页代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>聊天</title>
 <style type="text/css">
  #show{
   width: 600px;
   height: 300px;
   overflow-y: scroll;
  }
  .my-message{
   background-color: rgba(105, 105, 105, 0.64);
   color: #9e0505;
   width: 200px;
   float: right;
   padding: 10px;
  }
  .other-message{
   background-color: rgba(105, 105, 105, 0.64);
   color: #9e0505;
   width: 200px;
   float: left;
   padding: 10px;
  }
 </style>
</head>
<body>
 <div id="show"></div>
 <div class="panel">
  内容:<textarea id="content"></textarea>
  收信人:<input type="text" id="touser">
  <input type="button" id="send-btn" value="发送">
  <input type="button" id="close-btn" value="关闭">
 </div>
</body>
<script src="__PUBLIC__/js/jquery-1.10.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
 var socket = new WebSocket("wss://域名");
 $("#close-btn").click(function () {
  socket.close();
 })
 $("#send-btn").click(function () {
  var touser = $("#touser").val();
  var content = $("#content").val();
  var htmlstr = "<div><p class=\'my-message\'>我:"+content+"</p></div>";
  $("#show").append(htmlstr);
  socket.send(content+"@"+touser);
 })
 socket.onmessage = function (p1) {
  var htmlstr = "<div><p class=\'other-message\'>"+p1.data+"</p></div>";
  $("#show").append(htmlstr);
 }
</script>
</html>

2、小程序端的代码

Uitls/websocket.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var url = \'wss://www.xxx.cn\';//服务器地址
function connect(user, func) {
 wx.connectSocket({
 url: url,
 header: { \'content-type\': \'application/json\' },
 success: function () {
  console.log(\'websocket连接成功~\')
 },
 fail: function () {
  console.log(\'websocket连接失败~\')
 }
 })
 wx.onSocketOpen(function (res) {
 wx.showToast({
  title: \'websocket已开通~\',
  icon: "success",
  duration: 2000
 })
 //接受服务器消息
 wx.onSocketMessage(func);//func回调可以拿到服务器返回的数据
 });
 wx.onSocketError(function (res) {
 wx.showToast({
  title: \'websocket连接失败,请检查!\',
  icon: "none",
  duration: 2000
 })
 })
}
//发送消息
function send(msg) {
 wx.sendSocketMessage({
 data: msg
 });
}
module.exports = {
 connect: connect,
 send: send
}

JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// pages/socks/socks.js
const app = getApp()
var websocket = require(\'../../utils/websocket.js\');
var utils = require(\'../../utils/util.js\');
Page({
 /**
 * 页面的初始数据
 */
 data: {
 newslist: [],
 userInfo: {},
 scrollTop: 0,
 increase: false,//图片添加区域隐藏
 aniStyle: true,//动画效果
 message: "",
 previewImgList: []
 },
 /**
 * 生命周期函数--监听页面加载
 */
 onLoad: function () {
 var that = this
 if (app.globalData.userInfo) {
  this.setData({
  userInfo: app.globalData.userInfo
  })
 }
 //调通接口
 websocket.connect(this.data.userInfo, function (res) {
  // console.log(JSON.parse(res.data))
  var list = []
  list = that.data.newslist
  list.push(JSON.parse(res.data))
  that.setData({
  newslist: list
  })
 })
 },
 // 页面卸载
 onUnload() {
 wx.closeSocket();
 wx.showToast({
  title: \'连接已断开~\',
  icon: "none",
  duration: 2000
 })
 },
 //事件处理函数
 send: function () {
 var flag = this
 if (this.data.message.trim() == "") {
  wx.showToast({
  title: \'消息不能为空哦~\',
  icon: "none",
  duration: 2000
  })
 } else {
  setTimeout(function () {
  flag.setData({
   increase: false
  })
  }, 500)
  websocket.send(\'{ "content": "\' + this.data.message + \'", "date": "\' + utils.formatTime(new Date()) + \'","type":"text", "nickName": "\' + this.data.userInfo.nickName + \'", "avatarUrl": "\' + this.data.userInfo.avatarUrl + \'" }\')
  this.bottom()
 }
 },
 //监听input值的改变
 bindChange(res) {
 this.setData({
  message: res.detail.value
 })
 },
 cleanInput() {
 //button会自动清空,所以不能再次清空而是应该给他设置目前的input值
 this.setData({
  message: this.data.message
 })
 },

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
微信小程序导入微信聊天记录文件发布时间:2022-07-18
下一篇:
微信小程序正式上线 可置于聊天窗口顶部发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap