至少证明swoole还是活着的吧。。
zSwooleServer.php
<?php
class myServer {
public $server;
public $clients = array();
function __construct($ip, $port){
$this->server = new swoole_websocket_server($ip, $port);
//info
echo "swoole {$ip}, {$port} \n";
//client request
$this->server->on("open", function($s, $request){
echo "欢迎新玩家 {$request->fd} \n";
$clients[] = $request->fd;
});
$this->server->on("message", function($s, $frame) {
echo "玩家 {$frame->fd} \n";
echo "发来 {$frame->data} \n";
echo "操作码是 {$frame->opcode} \n}";
echo "fin是 {$frame->finish} \n}";
});
$this->server->on("close", function($s, $fd){
//delete the client from list
$key = array_search($this->clients, $fd);
unset($this->clients[$key]);
//broadcast
if(empty($clients)){
echo "没有玩家在线\n";
} else {
foreach($clients as $player){
$this->server->push($player, "玩家{$fd}下线了 \n");
};
}
});
$this->server->on("request", function($request, $response){
});
$this->server->start();
}
}
$s = new myServer("192.168.1.2", 9688);
?>
zSwooleClient.html
<html>
<head>
<meta charset="utf-8" />
<title>zSwooleClient</title>
<meta name="keywords" content="swoole,websocket,client"/>
<meta name="description" content="try html to connect swoole server"/>
</head>
<body>
<script>
var supportWS = false;
var ws;
function isSupport(){
if ("WebSocket" in window){
alert("browser support websocket");
supportWS = true;
} else {
alert("not support");
}
}
function con(){
if (supportWS) {
ws = new WebSocket("ws://192.168.1.2:9688");
ws.onopen = function(e){
alert("open");
};
ws.onmessage = function(e){
alert("message");
};
ws.onclose = function(e){
alert("close");
};
ws.onerror = function(e){
alert("error");
}
}
}
function send(){
//ws.send();
}
</script>
<div><button onClick="javascript:isSupport()" style="width:200px;height:200px">isSupport</button></div<
<div><button onClick="javascript:con()" style="width:200px;height:200px">con</button></div>
</body>
</html>