socket.php
<?php//创建websocket服务器对象,监听0.0.0.0:9502端口$ws = new swoole_websocket_server("0.0.0.0", 9503);//监听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();
socket.html
<!DOCTYPE html><html><head> ???<meta charset="UTF-8"> ???<title>socket</title></head><body>123</body><script> ???var wsServer = ‘ws://192.168.70.167:9503‘; ???var websocket = new WebSocket(wsServer); ???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); ???}; ???websocket.onerror = function (evt, e) { ???????console.log(‘Error occured: ‘ + evt.data); ???};</script></html>
socket.php,socket.html 目录/usr/local/nginx/html/下
启动socket.php:
# php socket.php
启动socket.html
浏览器打开:192.168.70.167/socket.html
swoole webSocket服务
原文地址:https://www.cnblogs.com/wesky/p/9448022.html