<?php /** * Created by PhpStorm. * User: Ty_Ro * Date: 2019/1/31 * Time: 16:20 */ //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $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> <script> var wsServer = "ws://106.14.14.231:9502"; var webSocket = new WebSocket(wsServer); webSocket.onopen = function (ev) { console.log("链接成功") } webSocket.onclose = function (ev) { console.log("关闭") } webSocket.onmessage = function (ev) { console.log(ev.data) } webSocket.onerror = function (ev) { console.log("error") } </script> </body> </html>