php——websocket

來源:互聯網
上載者:User

標籤:1.2   each   new   nec   事件   onclick   ges   .com   建立   

//建立websocket伺服器對象,監聽0.0.0.0:9502連接埠$ws = new swoole_websocket_server("0.0.0.0", 9502);//監聽WebSocket串連開啟事件$ws->on(‘open‘, function ($ws, $request) {    $fd[] = $request->fd;    $GLOBALS[‘fd‘][] = $fd;    //$ws->push($request->fd, "hello, welcome\n");});//監聽WebSocket訊息事件$ws->on(‘message‘, function ($ws, $frame) {    $msg =  ‘from‘.$frame->fd.":{$frame->data}\n";//var_dump($GLOBALS[‘fd‘]);//exit;    foreach($GLOBALS[‘fd‘] as $aa){        foreach($aa as $i){            $ws->push($i,$msg);        }    }   // $ws->push($frame->fd, "server: {$frame->data}");    // $ws->push($frame->fd, "server: {$frame->data}");});//監聽WebSocket串連關閉事件$ws->on(‘close‘, function ($ws, $fd) {    echo "client-{$fd} is closed\n";});$ws->start();

  

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div id="msg"></div><input type="text" id="text"><input type="submit" value="發送資料" onclick="song()"></body><script>    var msg = document.getElementById("msg");    var wsServer = ‘ws://192.168.1.253:9502‘;    //調用websocket對象建立串連:    //參數:ws/wss(加密)://ip:port (字串)    var websocket = new WebSocket(wsServer);    //onopen監聽串連開啟    websocket.onopen = function (evt) {        //websocket.readyState 屬性:        /*        CONNECTING    0    The connection is not yet open.        OPEN    1    The connection is open and ready to communicate.        CLOSING    2    The connection is in the process of closing.        CLOSED    3    The connection is closed or couldn‘t be opened.        */        msg.innerHTML = websocket.readyState;    };    function song(){        var text = document.getElementById(‘text‘).value;        document.getElementById(‘text‘).value = ‘‘;        //向伺服器發送資料        websocket.send(text);    }      //監聽串連關閉//    websocket.onclose = function (evt) {//        console.log("Disconnected");//    };    //onmessage 監聽伺服器資料推送    websocket.onmessage = function (evt) {        msg.innerHTML += evt.data +‘<br>‘;//        console.log(‘Retrieved data from server: ‘ + evt.data);    };//監聽串連錯誤資訊//    websocket.onerror = function (evt, e) {//        console.log(‘Error occured: ‘ + evt.data);//    };</script></html>

  

websocket API 手冊:
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

php——websocket

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.