swoole webSocket服务

时间:2025-03-14 14:04:37

socket.php

<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", ); //监听WebSocket连接打开事件 (刚打开的时候会给客户端发送 Hello,welcome)
$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> </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服务

其他写法:

以循环的方式给每一个用户发送信息

$ws->on('message', function ($ws, $frame) {
//echo "接收到的信息: {$frame->data}\n";
//$ws->push($frame->fd, "server: {$frame->data}");
//echo "服务器已接收:【".$frame->fd."】";
//$ws->push($frame->fd, json_encode(['hello','world'.$frame->data])); // 1.客户端发送过来的信息
$content = $frame->data;
echo "服务器接收到信息:".$content."\n";
// 2.讲消息发送个所有客户端
$arr = json_decode($content);
$id = $arr[];
$str= $arr[]; //一对一推送
$ws->push($id,$str);
// 一对多,推送 (循环方式给每一个客户端发送信息)
/*foreach ($ws->connections as $fd){
//echo "FD:".$fd."\n";
$arr = json_decode($content);
$id = $arr[0];
$str= $arr[1]; $ws->push($fd,$str);
}*/
});