一个简单的基于swoole的websocket实例。
服务端程序(websocket.php,来源swoole官网):
<?php $server = new swoole_websocket_server("0.0.0.0", 9501); $server->on(' open ', function (swoole_websocket_server $server, $ request ) { echo "server: handshake success with fd{$request->fd}\n"; }); $server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "this is server"); }); $server->on(' close ', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start(); ?>
客户端程序(client. html ):
<html>
<head>
<meta charset="UTF-8">
<title>Web sockets test</title>
<script src="jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
var ws;
function ToggleConnectionClicked() {
try {
ws = new WebSocket("ws://0.0.0.0:9501");//连接服务器
ws.onopen = function(event){
alert ("已经与服务器建立了连接,当前连接状态:"+this.readyState);
};
ws.onmessage = function(event){
alert("接收到服务器发送的数据:"+event.data);
};
ws.onclose = function(event){
alert("已经与服务器断开连接,当前连接状态:"+this.readyState);
};
ws.onerror = function(event){
alert("WebSocket异常!");
};
} catch (ex) {
alert(ex.message);
}
};
function SendData() {
try{
ws.send("Hello World");
}catch(ex){
alert(ex.message);
}
};
function seeState(){
alert(ws.readyState);
}
</script>
</head>
<body>
<button type="button" onclick='ToggleConnectionClicked();'>连接服务器</button><br />
<button type="button" onclick='SendData();'>发送Hello World</button><br />
<button type="button" onclick='seeState();'>查看状态</button><br />
</body>
</html>
在cli模式下执行:php websocket.php
在浏览器中访问 client.html