html 测试websocket

参考: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>  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值