1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
一.服務(wù)器端: 1. 編輯server.php文件內(nèi)容如下: <?php $reqs=array(); //保持客戶端的長(zhǎng)連接在這個(gè)數(shù)組里 $serv = new swoole_websocket_server("192.168.2.115", 9502); //如下可以設(shè)置多端口監(jiān)聽(tīng) //$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE); //$server->addlistener('0.0.0.0', 9502, SWOOLE_SOCK_UDP); //$server->set(['worker_num' => 4]); $serv->on('Open', function($server, $req) { global $reqs; $reqs[]=$req->fd; echo "connection open: ".$req->fd."\n"; var_dump(count($reqs));//輸出長(zhǎng)連接數(shù) }); $serv->on('Message', function($server, $frame) { global $reqs; echo "message: ".$frame->data."\n"; foreach($reqs as $fd){ $server->push($fd, $frame->data); } }); $serv->on('Close', function($server, $fd) { echo "connection close: ".$fd."\n"; }); $serv->start();12345678910111213141516171819202122232425262728 2. 啟動(dòng)上面實(shí)現(xiàn)的websocket服務(wù)代碼 [songaimin@localhost Tests]$/usr/bin/php server.php1 客戶端-同事打開(kāi)兩個(gè)瀏覽器模擬多client: 3. 在瀏覽器console里運(yùn)行: var wsl= 'ws://192.168.2.115:9502' ws = new WebSocket(wsl);//新建立一個(gè)連接 //如下指定事件處理 ws.onopen = function(){ws.send('Test!'); }; ws.onmessage = function(evt){console.log(evt.data);/*ws.close();*/}; ws.onclose = function(evt){console.log('WebSocketClosed!');}; ws.onerror = function(evt){console.log('WebSocketError!');}; 1234567 4. 在任意瀏覽器console里手動(dòng)執(zhí)行: ws.send(888); //看每個(gè)瀏覽器的內(nèi)容console輸出應(yīng)該是一樣的就實(shí)驗(yàn)在成功了 ws.close();//關(guān)閉連接
- 1 回答
- 0 關(guān)注
- 849 瀏覽
添加回答
舉報(bào)