<?php
error_reporting(0);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 9090);
socket_listen($socket, 5);
$allSockets = [$socket];
while (true) {
$copySockets = $allSockets; //因为socket_select的参数是引用传值,如果不重新赋值会一直被更改...
if (socket_select($copySockets, $write, $except, 0) === false) {
exit('error');
}
if (in_array($socket, $copySockets)) {
$client = socket_accept($socket);
$buff = socket_read($client, 1024);
if (false !== strpos($buff, 'Sec-WebSocket-Key:')) { //用正则也可以
$buf = substr($buff, strpos($buff, 'Sec-WebSocket-Key:') + 18);
$key = trim(substr($buf, 0, strpos($buf, "\r\n")));
$new_key = base64_encode(sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
$new_message = "HTTP/1.1 101 Switching Protocols\r\n"; //PHP_EOL
$new_message .= "Upgrade: websocket\r\n";
// $new_message .= "Sec-WebSocket-Version: 13\r\n";
$new_message .= "Connection: Upgrade\r\n";
$new_message .= "WebSocket-Location: ws://127.0.0.1:9090\r\n";
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
socket_write($client, $new_message, strlen($new_message)); //与client握手成功
socket_write($client, encodeMsg('hello websocket'));
$allSockets[] = $client; //将客户端加入socket_select监听的数组中
}
$key = array_search($socket, $copySockets); //server端连接时并不需要被读取,所以移除掉
unset($copySockets[$key]);
}
foreach ($copySockets as $s) {
$buf = socket_read($s, 8024);
if (strlen($buf) < 9) { //表示客户端主动关闭,比如浏览器刷新的一瞬间
$key = array_search($s, $copySockets); //同时移除掉此次连接
unset($copySockets[$key]);
socket_close($s); //此时服务端需主动关闭客户端的连接
continue;
}
echo decodeMsg($buf); //获取输出客户端发送来的信息
echo PHP_EOL;
}
// socket_close($client); //websocket服务端不会主动关闭连接,否则连接没有意义
}
socket_close($socket);
//解码客户端发送过来的消息
function decodeMsg($buffer) {
$len = $masks = $data = $decoded = null;
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
}
else if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
}
else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
//
for ($index = 0; $index < strlen($data); $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
}
return $decoded;
}
//编码发送给客户端的数据
function encodeMsg($msg)
{
$frame = [];
$frame[0] = '81';
$len = strlen($msg);
if ($len < 126) {
$frame[1] = $len < 16 ? '0' . dechex($len) : dechex($len);
} else if ($len < 65025) {
$s = dechex($len);
$frame[1] = '7e' . str_repeat('0', 4 - strlen($s)) . $s;
} else {
$s = dechex($len);
$frame[1] = '7f' . str_repeat('0', 16 - strlen($s)) . $s;
}
$data = '';
$l = strlen($msg);
for ($i = 0; $i < $l; $i++) {
$data .= dechex(ord($msg{$i}));
}
$frame[2] = $data;
$data = implode('', $frame);
return pack("H*", $data);
}
前端页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="sendMessage()">发送消息</button>
</body>
<script type="text/javascript">
if (!"WebSocket" in window) {
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
var ws = new WebSocket("ws://127.0.0.1:9090");
//ws协议
ws.onopen = function () {
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send("发送初始数据");
// console.log("数据发送中...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log("数据已接收...");
console.log(received_msg);
};
ws.onclose = function () {
// 关闭 websocket
console.log("连接已关闭...");
};
function sendMessage() {
ws.send('hi i am websocket client');
}
</script>
</html>