前端代码
想做前端websocket为二进制传输转吗,字节码转成中文,后端swoole传到前端的文字可解码,前端传后端目前我不会,暂时记录后期在解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
try {
var pageTile = document.title;
var ws;
var wsUrl = "ws://localhost:9502/connect?id=" + 1;
ws = new WebSocket(wsUrl);
ws.binaryType = "arraybuffer";
ws.onopen = function () {
//发送登录信息
this.send("。。。。。");
};
ws.onmessage = onmessage;
ws.onerror = function (e) {
};
/**
* 接收信息
*/
function onmessage(e) {
var data = e.data;
let v = new DataView(data);
// let code=(new DataView(data)).getUint8(0);
// console.log(code)
function ab2str(code, decodeType = "utf-8") {
// 默认是uft-8格式
let decoder = new TextDecoder(decodeType);
return decoder.decode(code);
}
let strArr = [];
for (let i = 0; i < v.byteLength; i++) {
strArr.push(v.getUint8(i));
}
let str = ab2str(new Uint8Array(strArr));
console.log(str); //
}
setInterval(function () {
ws.send("asd")
}, 10000);
} catch (e) {
console.log(e);
}
function stringToByte(str) {
const bytes = [];
let c;
let len = str.length;
for (var i = 0; i < len; i++) {
c = str.charCodeAt(i);
if (c >= 0x010000 && c <= 0x10FFFF) {
// 4个字节范围
bytes.push(((c >> 18) & 0x07) | 0xF0);
bytes.push(((c >> 12) & 0x3F) | 0x80);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if (c >= 0x000800 && c <= 0x00FFFF) {
// 3个字节范围
bytes.push(((c >> 12) & 0x0F) | 0xE0);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if (c >= 0x000080 && c <= 0x0007FF) {
// 2个字节范围
bytes.push(((c >> 6) & 0x1F) | 0xC0);
bytes.push((c & 0x3F) | 0x80);
} else {
// 1个字节范围
bytes.push(c & 0xFF);
}
}
return bytes;
}
var a = stringToByte("a你");
setTimeout(function () {
ws.send(stringToByte("你好!我是吴彦祖"));
}, 3000);
</script>
<div style="margin: 0 auto;">
<h1>websocket测试</h1>
</div>
</body>
</html>
<?php
$server = new Swoole\Websocket\Server('127.0.0.1', 9502);
$server->on('start', function ($server) {
echo "Websocket Server is started at ws://127.0.0.1:9502\n";
});
$server->on('open', function ($server, $req) {
echo "connection open: {$req->fd}\n";
});
$server->on('message', function ($server, $frame) {
var_dump($frame->data);
$data=explode(',',$frame->data);
var_dump($data);
$server->push($frame->fd, "a你", 2);
});
$server->on('close', function ($server, $fd) {
echo "connection close: {$fd}\n";
});
$server->start();