微信小程序 swoole简单聊天室

1 篇文章 0 订阅
1 篇文章 0 订阅

第一步在linux创建php即时通讯文件

<?php
//服务器代码
//创建websocket 服务器
$ws = new swoole_websocket_server("0.0.0.0",9501);
// open
$ws->on('open',function($ws,$request){
    echo "新用户 $request->fd 加入。\n";
    $GLOBALS['fd'][$request->fd]['id'] = $request->fd;//设置用户id
    $GLOBALS['fd'][$request->fd]['name'] = '匿名用户';//设置用户名

});
//message
$ws->on('message',function($ws,$request){
    $msg = $GLOBALS['fd'][$request->fd]['name'].":".$request->data."\n";
    if(strstr($request->data,"#name#")){//用户设置昵称
        $GLOBALS['fd'][$request->fd]['name'] = str_replace("#name#",'',$request->data);

    }else{//进行用户信息发送
        //发送每一个客户端
        foreach($GLOBALS['fd'] as $i){
            $ws->push($i['id'],$msg);
        }
    }
    echo('连接成功');
});
//close
$ws->on('close',function($ws,$request){
    echo "客户端-{$request} 断开连接\n";
    unset($GLOBALS['fd'][$request]);//清楚连接仓库
});


$ws->on('receive', function (\Swoole\Server $server, $fd, $reactor_id, $data)
{
if ($data == 'ping')
{
checkDB();
checkServiceA();
checkRedis();
$server->send('pong');
}
});


 

$server->set([
'worker_num' => 1,
'open_tcp_keepalive' => 1, // 开启tcp_keepalive
'tcp_keepidle' => 4, // 4s没有数据传输就进行检测
'tcp_keepinterval' => 1, // 1s探测一次
'tcp_keepcount' => 5, // 探测的次数,超过5次后还没有回包close此连接
]);

$ws->start();
 

第二步运行php文件 若是运行报错检查端口是否被占用占用

netstat -tunlp

若是占用 杀死端口进程 kill 断开id

 微信小程序视图层代码


<view>
  <view class="sendmessage">
    <input id="message" bindblur="inputMessage" placeholder="请输入聊天内容"></input>
    <button bindtap="sendMessage">发送</button>
  </view>
</view>
 
<view>
  <scroll-view scroll-y="true" class="history">
  <rich-text nodes="{{messages}}"></rich-text>
  <view style="width: 95%; height: 35px; font-size: 25px; text-align: center; line-height: 25px; margin-left: 2.5%;">{{list}}</view>
  </scroll-view>
</view>

微信小程序 js端代码

let socketOpen = false
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    content:"",
    messages:""
  },
  messages(msg) {
    if (socketOpen) {

      wx.sendSocketMessage({
        data:msg
      })
    }
  },
  inputMessage(e){
    this.setData({
      content:e.detail.value
    })
  },
  sendMessage:function(){
    this.messages(this.data.content)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    wx.connectSocket({
      url: 'ws://0.0.0.0:9501'
    })
    wx.onSocketOpen(function(res) {
      socketOpen = true
    })
    wx.onSocketMessage(function (res) {
      console.log(res)
  
      that.setData({
        messages:that.data.messages.concat('<br>'+res.data)
      })
    })
    wx.onSocketClose((res) => {
      console.log(res)
      if(res.code==1006)
      {
       that.setData({
         list:'自动断开连接,请刷新后在试'
       })
      }
    })
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
 
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
 
  },
 
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
 
  },
 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
 
  },
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
 
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
 
  }
})

可在写一个http客户端方便测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script></script>
</head>
<body>

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title id="myTitle">IM</title>
</head>
<style>
    body {
        background-color: palegreen;
    }
    #myname {
        width:120px;
        height:30px;
        border-radius: 20px;
    }
    .setUserName {
        width:80px;
        height:30px;
        background-color: cornflowerblue;
        font-weight: bold;
    }
    #msg{
        margin:80px 300px;
        width:450px;
        height:200px;
        background-color:white;
    }
    .show_send{
        margin:0px 300px;
    }
    #text{
        width:300px;
        height:30px;
    }
    .send_button{
        width:80px;
        height:30px;
        background-color: #4288ce;
        border-radius: 20px;
        color: white;
        font-weight: bold;
    }
</style>
<body>
<h1 align="center" style="color: white">swoole-websocket 及时通讯demo</h1>
<!--发送信息-->
<div id="send_msg" class="main box-shadow" style="display:none;">
    <div id="msg"></div>
    <div class="show_send">
        <input type="text" id="text" placeholder="请输入内容"><input class="send_button" value="发送" type="submit" onclick="send_message()">
    </div>
</div>
<!--设置昵称-->
<div id="setName" class="box-shadow" style="display:block;margin:200px 150px 200px 550px;">
    <lable>请输入你的昵称!</lable>
    <br>
    <input type="text" id="myname"/>
    <input type="submit" class="setUserName" value="设置昵称" onclick="send_name()">
</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    var msg = document.getElementById("msg");
    var wsServer = 'ws://0.0.0.0:9501';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function(evt){
        // msg.innerHTML = websocket.readyState;
        /*
         connecting 0
         open 1
         closing 2
         closed 3

        */
    }
    websocket.onmessage = function(evt){
        msg.innerHTML += evt.data+'<br />';
        console.log('从服务器获取到的数据:'+ evt.data);
    }
    
    websocket.onclose = function(evt){
        alert('自动断开');
    }
    websocket.onerror = function(evt,e){
        console.log('错误:'+evt.data);
    }
    function send_message(){
        var text = document.getElementById('text').value;
        document.getElementById('text').value = '';
        websocket.send(text);
    }
    function send_name(){
        var text = document.getElementById('myname').value;
        websocket.send("#name#"+text);
        var myTitle = document.getElementById("myTitle");
        myTitle.innerHTML = "IM" +text;
        alert("设置成功");
        var setName = document.getElementById("setName");
        setName.style.display = "none";
        var send_msg = document.getElementById("send_msg");
        send_msg.style.display = "block";
    }
</script>
</html>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值