swoole+redis(websocket聊天室demo)

  websocket是不一樣於http的另一種網絡通訊協議,可以進行雙向通訊,基於此,可開發出各類實時通訊產品,我簡單作了個聊天室demo,順便分享一下。javascript

  PHP的swoole擴展,正如做者所說,是PHP的異步、並行、高性能網絡通訊引擎,使用純C語言編寫,提供了PHP語言的異步多線程服務器異步TCP/UDP網絡客戶端異步MySQL異步Redis數據庫鏈接池AsyncTask消息隊列毫秒定時器異步文件讀寫異步DNS查詢。 Swoole內置了Http/WebSocket服務器端/客戶端Http2.0服務器端php

  本demo用swoole來作server端,client端使用html5 websocket api,使用redis set數據結構存儲鏈接標識。具體代碼以下:html

  1,websocket.php:html5

  

<?php
/**
 * Created by PhpStorm.
 * User: purelightme
 * Date: 2017/7/30
 * Time: 15:24
 */
$ws_server = new swoole_websocket_server('0.0.0.0', 9502);

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//$redis->flushAll();exit;

$ws_server->on('open', function ($ws, $request) use ($redis) {
    $redis->sAdd('fd', $request->fd);
});

$ws_server->on('message', function ($ws, $frame) use ($redis) {
    global $redis;
    $fds = $redis->sMembers('fd');
    foreach ($fds as $fd){
        $ws->push($fd,$frame->fd.'--'.$frame->data);
        //發送二進制數據:
        $ws->push($fd,file_get_contents('http://imgsrc.baidu.com/imgad/pic/item/267f9e2f07082838b5168c32b299a9014c08f1f9.jpg'),WEBSOCKET_OPCODE_BINARY);
    }
});

//監聽WebSocket鏈接關閉事件
$ws_server->on('close', function ($ws, $fd) use ($redis) {
    $redis->sRem('fd',$fd);
});

$ws_server->start();

  2,websocket.html:java

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <script type="text/javascript">
        if(window.WebSocket){
            var webSocket = new WebSocket("ws://0.0.0.0:9502");
            webSocket.onopen = function (event) {
                //webSocket.send("Hello,WebSocket!");
            };
            webSocket.onmessage = function (event) {
                var content = document.getElementById('content');
                if(event.data instanceof Blob) {
                    var img = document.createElement("img");
                    img.src = window.URL.createObjectURL(event.data);
                    content.appendChild(img);
                }else {
                    content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">用戶id-'+event.data+'</p>');
                }
            };

            var sendMessage = function(){
                var data = document.getElementById('message').value;
                webSocket.send(data);
                document.getElementById('message').value = '';
            }
        }else{
            console.log("您的瀏覽器不支持WebSocket");
        }
    </script>
</head>
<body>
<div style="width:600px;margin:0 auto;border:1px solid #ccc;">
    <div id="content" style="overflow-y:auto;height:300px;"></div>
    <hr/>
    <div style="height:40px">
        <input type="text" id="message" style="margin-left:10px;height:25px;width:450px;">
        <button onclick="sendMessage()" style="height:28px;width:75px;">發送</button>
    </div>
</div>
</body>
</html>

  效果大概以下圖,感興趣的能夠本身研究研究。。。mysql

相關文章
相關標籤/搜索