微信小程序实现即时通信聊天功能的实例代码
项目背景:小程序中实现实时聊天功能
一、服务器域名配置
配置流程
配置参考网址:https://开发者。微信。QQ。com/mini program/dev/API/API-网络。超文本标记语言
二、nginx中配置反向代理加密网络套接字(wss)
上游websocket{ hash $remote_addr一致;服务器127.0.0.1:9090权重=5 max _ failed=3 fail _ time out=30s;}服务器{听80服务器名www.xxxx.cn;重写^(.*)$ https://$主机$1永久;}服务器{听443服务器名www.xxxx.cn;安全套接层打开;root/home/wwwroot/yzcp;index.phpindex.htmlindex.htm指数;SSL _ certificate/usr/local/nginx/conf/cert/1526060965511。质子交换膜;#这里是服务端证书路径SSL _ certificate _ key/usr/local/nginx/conf/cert/1526060965511。钥匙;#这里是密钥路径SSL _ session _ time out 5mSSL _ ciphers ECD he-RSA-AES 128-GCM-sha 256: ECD he : ECD h : AES : high :NULL:aNULL:MD5:ADH:RC4;SSL _协议TLS v1 TLS v1。1 TLS v1。2;SSL _ prefere _ server _ ciphers onsl _ verify _ client关闭;#隐藏index.php位置/{ #索引index.php;拒绝127 .0 .0 .1;if(!-e $request_filename) { #一级目录重写^(.*)$ /index.php?s=最后$ 1;打破;} #wss配置client _ max _ body _ size代理_重定向关闭;proxy _ pass http://websocket#反向代理转发地址proxy _ set _ header主机$ host# http请求的主机域名proxy _ set _ header X-Real-IP $ remote _ addr;# 远程真实互联网协议(互联网协议)地址proxy _ set _ header _ X-forward-For $ proxy _ add _ X _ forward _ For;#反向代理之后转发之前的互联网协议(互联网协议)地址proxy _ read _ time out 604800s # web socket心跳时间,默认是60s代理_ http _ version 1.1 proxy _ set _ header Upgrade $ http _ Upgrade;代理集头连接"升级";}地点~。\.PHP { fastcgi _ pass UNIX :/tmp/PHP-CGI。袜子;index.php指数;包括fastcgi _ params设置$ path _ info设置$ real _ script _ name $ fastcgi _ script _ name;if ($fastcgi_script_name ~ '^(.\.PHP()/.)$ '){ set $ real _ script _ name $ 1;设置$ 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;} #防盗链开始位置~。*\.(gif | jpg | JPEG | png | BMP | swf)$ { 0过期30天;}地点~。*\.(js|css)?$ {过期12小时;} access _ log/home/www . log/www . 1537 ucn。日志;}三、安装框架
编译安装:
wget http://pecl.php.net/get/swoole-1.9.3.tgz/下载swoole tar-zvxf swoole-1。9 .3 .tgz/解压swoolecd swoole-1。9 .3/;//进入swoole/usr/local/PHP 54/bin/PHP ize;//生成配置/config-with-PHP-config=/usr/local/PHP/bin/PHP-config make/install安装CD/PHP study/server/PHP/lib/PHP/extensions/no-debug-non-zts-20121212//查看是否安转上了swoole.so(注意:此文件下边都是你安装的拓展)vim/PHP study/server/PHP/etc/PHP。ini/在php.ini添加extension=swoole.so加入到文件最后一行服务器重启;//重启nginx PHP-m;//查看phpinfo,这时候框架拓展已经装上了四、服务器端运行程序
1、创建server.php放到项目的根目录即可
?php/实例化一个框架的求转发到服务监听本机的9501端口$ server=new swoole _ web socket _ server('服务器IP ',9090);//只需要绑定要监听的互联网协议(互联网协议的缩写)和端口。如果互联网协议(互联网协议的缩写)指定为127.0.0.1,则表示客户端只能位于本机才能连接,其他计算机无法连接。//端口这里指定为9090,可以通过显示网络连接查看下该端口是否被占用。如果该端口被占用,可更改为其他端口,如9502,9503等$server-on('open ',函数(swoole_websocket_server $server,$request) { echo '你好连接成功{ $ request-FD } \ n ';});$server-on('消息',函数(swoole_websocket_server $server,$ frame){ foreach($ server-connections as $ key=$ FD){ $ user _ message=$ frame-data;$server-push($fd,$ user _ message);}});$server-on('close ',函数($ser,$ FD){ echo ' client { $ FD }已关闭\ n ';});$ server-start();2、由于swoole _服务器只能运行在硬币指示器(硬币水平指示器的缩写)命令行界面(批处理脚本的命令行界面)模式下,所以不要试图通过浏览器进行访问,这样是无效的,我们在命令行下面执行,注意一定要找到服务器端编程语言(专业超文本预处理器的缩写)的绝对路径PHP server.php(这行代码的意思是,把程序在服务器跑起来)
注意:PHP server.php命令运行后,下面的黑框关闭后将无法聊天。所以一般使用命令:nohup PHP server.php
五、客户端
1、网页代码
!DOCTYPE html html head meta charset=' utf-8 '标题聊天/title style type=' text/CSS ' # show { width : 600 px;高度: 300像素溢出-y:滚动;} .my-message {底色: rgba(105,105,105,0.64);color: # 9e0505宽度: 200像素;向右浮动:padding: 10px }。其他-消息{ background-color: rgba(105,105,105,0.64);color: # 9e0505宽度: 200像素;向左浮动:padd : 10px }/style/head body div id=' show '/div class=' panel '内容:textarea id='content'/textarea收信人:输入类型='text' id='touser '输入类型='button' id='send-btn' value='发送输入类型='button' id='close-btn' value='关闭/div/body脚本src=' http : _ _ PUBLIC _ _/js/jquery-1。10 .2 .量滴js ' charset=' utf-8 '/脚本脚本类型=' text/JavaScript ' var socket=new WebSocket(' WSS 3360//域名');$('#close-btn ').click(function(){ socket。close();}) $('#send-btn ').click(function(){ var touser=$(' # touser ')).val();var content=$(“# content”).val();var html str=' divp class=' my-message '我:"内容"/p/div;$('#show ').追加(html字符串);插座。send(内容“% @”touser);})套接字。on message=function(P1){ var html str=' divp class=' other-message ' ' P1。数据'/p/div ';$('#show ').追加(html字符串);}/script/html2、小程序端的代码
Uitls/websocket.js:
var URL=' WSS ://。XXX。cn ';//服务器地址函数连接(用户,功能){ wx。connectsocket({ URL : URL,标头: { ' content-type ' : ' application/JSON ' }),success : function(){ console。日志(' web套接字连接成功~') },失败:函数(){ console。日志(' web套接字连接失败~ ')} })wx。onscocketopen(函数(RES){ wx。showtoast({ title : ' web套接字已开通~ ',icon: 'success ',duration: 2000 }) //接受服务器消息wx。onscootmessage(func);//func回调可以拿到服务器返回的数据});wx.onSocketError(函数(RES){ wx。showtoast({ title : ' web套接字连接失败,请检查!',icon: "无",duration: 2000 }) })}//发送消息函数发送(消息){ wx。sendsocketmessage({ data : msg });}模块。导出={ connect : connect,send: send}JS:
//页数/袜子/短袜。jsconst app=GetApp()var web socket=require('././utils/web套接字。js’);var utils=require('././utils/util。js’);页面({ /** *页面的初始数据*/data : { newlist :[],userInfo: {},scrollTop: 0,increase: false,//图片添加区域隐藏aniStyle: true,//动画效果消息: ' ',预览列表: [] },/** *生命周期函数-监听页面加载*/onLoad:函数(){ var=this if(app。GlobalDATA。UserInfo){这个。setdata({ UserInfo : app。GlobalDATA。UserInfo })}//调通接口web套接字。连接(这个。数据。userinfo,函数(RES){//控制台。日志(JSON。解析(RES . data))var list=[]list=那个。数据。新列表。推送(JSON。解析(RES . data))该。setdata({ newlist : list })})},//页面卸载onUnload(){ wx。close socket();wx.showToast({ title: '连接已断开~ ',icon: 'none ',duration: 2000 }) },//事件处理函数send :函数(){ var flag=this if(this。数据。消息。trim()==' '){ wx。showtoast({ title : '消息不能为空哦~ ',icon: 'none ',duration 3360 2000 })else { setTimeout(function(){ flag }。setdata({ incremente : false })},500)web套接字。发送({ ' content ' : ' ' this。数据。消息“”,日期“:”实用程序。格式化时间(新日期())',键入' : '文本','昵称3: ' '这个。数据。用户信息。昵称。监听投入值的改变绑定更改(RES){ this。setdata({ message : RES . detail。value })},cleanInput() { //button会自动清空,所以不能再次清空而是应该给他设置目前的投入值这个。setdata({ message : this。数据。消息})},递增(){这个。setdata({ incremente : true,aniStyle: true }) },//点击空白隐藏消息下选框outn(){ this。setdata({ incremente : false,aniStyle: true }) },//发送图片选择image(){ var=this wx。选择图像({ count : 1,//默认9尺寸类型: ['原始','压缩'],//可以指定是原图还是压缩图,默认二者都有sourceType: ['相册','相机'],//可以指定来源是相册还是相机,默认二者都有成功:函数(res) { //返回选定照片的本地文件路径列表,tempFilePath可以作为图片标签的科学研究委员会属性显示图片var tempfile path=RES . tempfile path//console。日志(tempfilepath)wx。上传文件({ URL : ' WSS :///www。XXX。cn ',//服务器地址文件路径:临时文件路径[0],名称: '文件,标题: { '内容类型' : '表单数据},成功:函数如果数据。setdata({ increment : false })web套接字。发送(“{”图像“:”RES . data“、”日期“:”utils。格式化时间(新日期())”、键入“:”图像“、”昵称“:”那个。数据。用户信息。昵称”、“头像网址”:“那个。数据。用户信息。头像网址" })图片预览previewImg(e){ var=this//必须给对应的页面结构的图像标签设置数据集="图片路径",否则接收不到var RES=e . target。数据集。src var列表=这个。数据。previewimglist//页面的图片集合数组//判断表示留数在数组中是否存在,不存在则推到数组中, -1表示表示留数不存在if(列表。indexof(RES)==-1){ this。数据。预览列表。push(RES)} wx。预览图像({当前3360 RES,//当前显示图片的超文本传送协议(超文本传输协议的缩写)链接网址:数据。previewmglist//需要预览的图片超文本传送协议(超文本传输协议的缩写)链接列表}) }, //聊天消息始终显示最底端底部:函数(){ var query=wx。createselectorquery()。查询。选择(' # flag ').boundingClientRect()查询。选择视口().scrollOffset()。查询。exec()函数(RES){ wx。页面滚动到({滚动顶部: RES[0]).底部/节点的下边界坐标}) res[1].scrollTop //显示区域的竖直滚动位置}) },})WXML:
!-书页/袜子/袜子。wxml-view class=' news ' bind tap=' outt ' view class=' chat-note ' wx : if=' { { UserInfo } } '系统消息: 欢迎{{ userInfo.nickName }}加入聊天室/view view class=' history con ' scroll-view scroll-y=' true ' class=' history ' scroll-top=' { { scroll top } } ' block wx : for=' { { news list } } ' wx : key!-历史消息- !-view class=' chat-news ' view style=' text-align : left;左填充left : 20 rpximage class=' new _ img ' src=' http : { { item }。头像网址?项目。头像网址: '图片/avator。png ' } '/image text class=' name ' { item。昵称} } { { item。date } }/text/view class=' you _ left ' block wx : if=' { { item。type=' text ' } ' view class=' new _ txt ' { item。content } }/view/block block wx : if=' { { item。type=' image ' } ' image class=' selecting '-自己的消息-view class=' chat-news ' wx : if=' { { item。昵称==userInfo。昵称} }“view style=”text-align : right;填充-右: 20 rpxtext class=' name“{ item。昵称} }/text image class=' new _ img ' src=' http : { { user info。头像URL } } '/图像/视图类=' my _ right ' block wx : if=' { { item。type=' text ' } } ' view class=' new _ txt ' { item。content } }/view/block block wx : if=' { { item。type=' image ' } ' image class='-别人的消息-view class=' chat-news ' wx : elseview style=' text-align : left;左填充left : 20 rpximage class=' new _ img ' src=' http : { { item }。头像网址?项目。avatarurl : ' images/avator。png ' } '/image text class=' name ' { item。昵称} }/text/view view class=' you _ left ' block wx : if=' { { item。type=' text ' } ' view class=' new _ txt ' { item。content } }/view/block块wx 3360 if=' { { item。type=' image ' } ' image class=' selectImg ' src=' http 3-聊天输入-view class=' message ' form bind reset=' clean input ' class=' sendmail ' input type=' text ' placeholder='请输入聊天内容.'value=' { { message } } ' bind input=' bind change '/input view class=' add ' bind tap=' increment '/view button type=' primary ' bind tap=' send ' formType=' reset ' size=' small ' button-hover=' blue '发送/button/formview类='增加了{{aniStyle?向上滑动' : '向下滑动' } } ' wx : if=' { {增加} }“视图类=”图像”绑定点击=“选择图像”相册/view/view/viewxss 3360
/*书页/袜子/短袜。wxss */page {底色: # f7f 7;高度: 100%;}/* 聊天内容*/.新闻{ padding-top : 30 rpx;文本对齐:中心;/*高度:100%;*/盒尺寸:边框-盒子;} # flag { margin-bottom : 100 rpx;高度: 30rpx}。聊天-通知{ text-align :居中;font-size : 30 rpxpadd : 10 rpx 0;color: # 666}。历史con {高度: 100%;宽度: 100%;/*灵活方向:列;*/显示: flex边框-顶部: 0px}/* 聊天*/.聊天-新闻{宽度: 100%;飞越:隐藏;}.聊天新闻my _ right { float : right/* right : 40 rpx;*/padd : 10 rpx 10 rpx;}.聊天新闻名称{右边距: 10 rpx}.聊天新闻you _ left { float : left/* left : 5rpx;*/padd : 10 rpx 10 rpx;}.选择{显示:内嵌块;宽度: 150 rpx高度: 150 rpx左边距left: 50rpx}。我的右边。选择{右边距: 80 rpx}.new _ img { width : 60 rpxhire : 60 rpx边界半径: 50%;垂直对齐: 中间;右边距: 10 rpx}.new _ txt { max-width : 300 rpx;显示器:内联块;边界半径: 6rpx线高: 60 rpx背景-颜色: # 95d 4ffpadd : 5 rpx 20 rpxmargin : 0 10 rpx左边距left: 50rpx}。我的右边new _ txt { margin-right :60 rpx;}.您{背景色:浅绿色;}.我的{边框颜色:透明透明透明# 95d4ff}。您{边框-颜色:透明# 95d 4ff透明透明;}.hei { margin-top : 50px;高度: 20rpx}。历史{身高: 100%;页边距-top : 15px;padd : 10 rpx font-size : 14px;线高: 40px断字:断字;} :-web工具包-滚动条{ width : 0;高度: 0;颜色:透明;z指数:-1;}/* 信息输入区域*/.消息{位置:已修复;底部:0;宽度: 100%;}.发送消息{ display:块;高: 80 rpxpadding : 10 rpx 10 rpx背景-color : # fff;边框-top: 2rpx实心# eeeborder-bottom: 2rpx实心# eeez索引:3;}.发送消息输入{ float:left宽度: 66%;高度: 100%;线高: 80 rpx边框-底部: 1rpx实心# cccpadding :0 10 rpx font-size : 35 rpx;color: # 666}。发送消息视图{显示:内联块;宽度: 80 rpx高度: 80rpx线高: 80 rpxfont-size : 60 rpx文本对齐:中心;color: # 999border: 1rpx固体# ccc边界半径: 50%;左边距left: 10rpx}。发送消息按钮{右侧浮动:font-size : 35 rpx}.增加{宽度:100%;/*高度: 150 rpx*/padd : 40 rpx 30 rpx;背景-color : # fff;}.增加了。图像{ width: 100rpx高度: 100 rpxborder: 3rpx固体# ccc线高: 100 rpx文本对齐:中心;边界半径: 8 rpxfont-size :35 rpx} @关键帧从{transform: translateY(0)向下滑动;}到{ transform : translateY(100%);}}.下滑{animation:下滑0.5s线性;}.向上滑动{ animate :向上滑动0.5s线性;} @关键帧向上滑动{来自{ transform : translateY(100%);}到{ transform : translateY(0);}}总结
以上所述是小编给大家介绍的微信小程序实现即时通信聊天功能的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
版权声明:微信小程序实现即时通信聊天功能的实例代码是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。