参考:Blob转字符串(Blob to string) - 简书 (jianshu.com)
WebSocket的C++服务器端实现 - xmj - 博客园 (cnblogs.com)
注: memcpy(handler->getbuff(), pol->m_cRecvBuf, strlen(pol->m_cRecvBuf)); //memcpy 内存指针错误, strlen(pol->m_cRecvBuf)长度错误,不拷贝,改直接传地址
handler->setPbuff(pol->m_cRecvBuf);
inline void Websocket_Handler::setPbuff(char* buff) {
buff_ = buff;
}
html代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="https://github.com/jice1001" />
<title>websocket test</title>
<script>
var socket;
function Connect(){
try{
let client = new WebSocket(document.getElementById("urls").value);
client.onopen = sOpen;
client.onerror = sError;
client.onmessage = sMessage;
client.onclose = sClose;
socket = client;
}catch(e){
alert('error');
return;
}
}
function sOpen(){
alert('connect success!');
}
function sError(e){
alert("error " + e);
}
function sMessage(msg) {
doReceive(msg.data);
}
function sClose(e){
alert("connect closed:" + e.code);
socket.close();
}
function Send(){
socket.send(document.getElementById("msg").value);
}
function Close() {
socket.close();
}
function doReceive(buffer) {
console.log("doReceive:");
// blob:待读取的blob对象 -- https://www.jianshu.com/p/72f12d27d3ba
buffer.text().then(data => {
// data:指成功读取到的内容
console.log(data);
alert('server says:' + data);
}).catch(err =>{
//err: 指读取失败后返回的错误内容
alert('no understand server says');
})
};
</script>
</head>
<body>
<input id="urls" type="text" value="ws://localhost:9000">
<input id="msg" type="text">
<button id="connect" onclick="Connect();">Connect</button>
<button id="send" onclick="Send();">Send</button>
<button id="close" onclick="Close();">Close</button>
</body>
</html>