通过"set api ws"命令可以将PHPoC启动为web socket server。 下面是web socket server使用例。
此例中连接web socket时,每秒传送 "hello, world"的句子。
$pid = pid_open("/mmap/tcp0"); // open TCP 0
pid_ioctl($pid, "set api ws"); // set api to web socket
pid_ioctl($pid, "set ws path WebConsole"); // set URI path: /WebConsole
pid_ioctl($pid, "set ws mode 0"); // set transmission mode: text
//pid_ioctl($pid, "set ws origin 10.1.0.1"); // specify a host to allow connection
pid_ioctl($pid, "set ws proto text.phpoc"); // protocol: text.phpoc
pid_bind($pid, "", 0); // binding: default(80)
while(1)
{
if(pid_ioctl($pid, "get state") == TCP_CLOSED)
pid_listen($pid); // listen TCP connection
pid_send($pid, "hello, world!\r\n"); // send data
sleep(1);
}
pid_close($pid);
下面是为了实行上面的例而需要的必要网页(index.php) 代码。
<html>
<head>
<title>PHPoC / <?echo system("uname -i")?></title>
<meta name="viewport" content="width=device-width, initial-scale=0.7">
<style>
body { text-align:center; }
textarea { width:400px; height:400px; padding:10px; font-family:courier; font-size:14px; }
</style>
<script>
var ws;
var wc_max_len = 32768;
function ws_onopen()
{
document.getElementById("ws_state").innerHTML = "OPEN";
document.getElementById("wc_conn").innerHTML = "Disconnect";
}
function ws_onclose()
{
document.getElementById("ws_state").innerHTML = "CLOSED";
document.getElementById("wc_conn").innerHTML = "Connect";
ws.onopen = null;
ws.onclose = null;
ws.onmessage = null;
ws = null;
}
function wc_onclick()
{
if(ws == null)
{
ws = new WebSocket("ws://<?echo _SERVER("HTTP_HOST")?>/WebConsole", "text.phpoc");
document.getElementById("ws_state").innerHTML = "CONNECTING";
ws.onopen = ws_onopen;
ws.onclose = ws_onclose;
ws.onmessage = ws_onmessage;
}
else
ws.close();
}
function ws_onmessage(e_msg)
{
e_msg = e_msg || window.event; // MessageEvent
var wc_text = document.getElementById("wc_text");
var len = wc_text.value.length;
if(len > (wc_max_len + wc_max_len / 10))
wc_text.innerHTML = wc_text.value.substring(wc_max_len / 10);
wc_text.scrollTop = wc_text.scrollHeight;
wc_text.innerHTML += e_msg.data;
}
function wc_clear()
{
document.getElementById("wc_text").innerHTML = "";
}
</script>
</head>
<body>
<h2>
<p>
Web Console : <span id="ws_state">CLOSED</span><br>
</p>
<textarea id="wc_text" readonly="readonly"></textarea><br>
<button id="wc_conn" type="button" onclick="wc_onclick();">Connect</button>
<button id="wc_clear" type="button" onclick="wc_clear();">Clear</button>
</h2>
</body>
</html>
在上面的例子中,web socket server (php script) 与 client (javascript)在PHPoC上构架的,web socket server在PHPoC上实行web socket client在网络浏览器上实行。 上面的流程图如下。
※ 利用web socket服务器(in task0.php)与基本网页服务器功能(in index.php)可更有效率的网络接口。
※ 为了在PC上使用web socket,必须使用支持web socket的浏览器。