websocket.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> var websocket = new WebSocket('ws://117.13.63.36:9502'); //192.338.139.103:9502 websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; </script> </html>
websocket.php
<?php $server = new SwooleWebsocketServer("0.0.0.0", 9502); $server->on('open', function($server, $req) { echo "connection open: {$req->fd} "; }); $server->on('message', function($server, $frame) { echo "received message: {$frame->data} "; $server->push($frame->fd, json_encode(["hello", "world"])); }); $server->on('close', function($server, $fd) { echo "connection close: {$fd} "; }); $server->start();
开启服务端 执行websocket.php 文件 然后运行html文件即可互相通信