1. 程式人生 > 其它 >PHP+Swoole 簡單聊天室

PHP+Swoole 簡單聊天室

html 程式碼

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <
link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> <script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="http://cdn.bootcss.com/socket.io/1.3.5/socket.io.js"
></script> </head> <body> <div id="box" style="max-width:700px;margin:0 auto;"> <div class="panel panel-default"> <div class="panel-heading"><h2>聊天室</h2><span style="color:green;display:none;">(當前線上:<span id="length">0</span
>人)</span></div> <div class="panel-body" id="body" style="height:400px;overflow-y:auto;"> </div> </div> <div class="input-group"> <input type="text" class="form-control" id="in" class="send" placeholder="您想說什麼?" aria-describedby="basic-addon2"> <span class="input-group-addon" id="basic-addon2" style="cursor:pointer;">傳送</span> </div> </div> <div class="modal fade bs-example-modal-sm" data-backdrop="static" id="model" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="input-group"> <input type="text" class="form-control" id="name" placeholder="請輸入您的暱稱" aria-describedby="basic-addon3"> <span class="input-group-addon" id="basic-addon3" style="cursor:pointer;">開始聊天</span> </div> </div> </div> </div> </body> <script> $(document).ready(function(){ window.username = 'others';
  //填寫自己的線上伺服器:冒號後是埠自己放開
var wsServer = 'ws://121.51.78.91:9502'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); $("#model").modal('show'); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); $(".panel-body").append(evt.data); //$(".panel-body").append('<p><span style="color:#177bbb">'+evt.data.username+'</span> <span style="color:#aaaaaa">('+evt.data.time+')</span>: '+evt.data.msg+'</p>'); var body = document.getElementById("body"); body.scrollTop = body.scrollHeight; $("#in").focus(); }; $("#in").keydown(function(e){ if(e.keyCode==13){ var msg = $("#in").val(); if(!msg){ alert('請輸入內容') return } websocket.send(msg); $("#in").val(''); } }); $("#basic-addon2").click(function(){ var msg = $("#in").val(); if(!msg){ alert('再請輸入內容) return } websocket.send(msg); $("#in").val(''); }); $("#basic-addon3").click(function(){ window.username = $("#name").val(); if(!window.username){ alert('請輸入內容') return } websocket.send("login|@|"+window.username); $("#model").modal('hide'); }); }); </script> </html>

php 程式碼

<?
date_default_timezone_set('PRC');
$users = array();
//建立websocket伺服器物件,監聽0.0.0.0:9502埠
$ws = new swoole_websocket_server("0.0.0.0", 9502);

$ws->set(array(
    'worker_num' => 1,
));

//監聽WebSocket連線開啟事件
$ws->on('open', function ($ws, $request) {
   // var_dump($request->fd, $request->get, $request->server);
    //global $users;
   // var_dump($users);
   // $users[] = $request->fd;
    //var_dump($users);
   //$ws->push($request->fd, "hello, welcome\n");
});


//監聽WebSocket訊息事件
$ws->on('message', function ($ws, $frame) {
    global $users;
//      var_dump($frame);
    $data = $frame->data;
    $arr = explode('n|@|',$data);
    if(count($arr)>1){
      $users[$frame->fd] = $arr[1];
      foreach($users as $fd=>$name){
         $ws->push($fd,'<p><span style="color:#177bbb">系統通知</span><span style="color:#aaaaaa">('.date('H:i:s').')</span>:'.$arr[1].'加入聊天</p>');
      }
    }else{
     // var_dump($users);
      foreach($users as $fd=>$name){
        //$msg = 'from'.$name.":{$frame->data}\n";
        $msg = '<p><span style="color:#177bbb">'.$users[$frame->fd].'</span> <span style="color:#aaaaaa">('.date('H:i:s').')</span>: '.$frame->data.'</p>';
        $ws->push($fd,$msg);
      }
    }

});

//監聽WebSocket連線關閉事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

放開埠號,然後執行PHP test.php //執行自己的PHP