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

前端之家收集整理的这篇文章主要介绍了微信小程序实现即时通信聊天功能的实例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

一、服务器域名配置

配置流程

配置参考URL:nofollow" href="https://developers.weixin.qq.com/miniprogram/dev/api/api-network.html">https://developers.weixin.qq.com/miniprogram/dev/api/api-network.html

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

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

编译安装:

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放到项目的根目录即可

on('open',function (swoole_websocket_server $server,$request) { echo "你好连接成功{$request->fd}\n"; }); $server->on('message',$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、网页代码

<Meta charset="utf-8"> 聊天