標籤: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