SignalR hub 的websocket 直连

本文介绍了如何在HTML页面中使用WebSocket技术建立与服务器的连接,实现文本输入区实时显示消息以及发送请求的功能。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <textarea id="textarea" style="height: 500px; width: 100%;"></textarea>
    <input type="button" id="send" onclick="connect()" value="连接">
    <input type="button" id="send" onclick="send()" value="给服务端发送消息">

    <script type="text/javascript">
        //检查浏览器是否支持WebSocket
        if (!window.WebSocket) {
            console.log('您的浏览器不支持WebSocket,请选择其他的浏览器再尝试连接服务器');
        }
        let el = document.getElementById("textarea");

        try {
            const wsClientSp2 = new WebSocket('ws://192.168.32.101:443/TelevisionHub');
            wsClientSp2.open = function (e) {
                el.value += "连接成功!\r\n";
            }
            wsClientSp2.onclose = function (e) {
                el.value += "连接断开!\r\n";
            }
            wsClientSp2.onmessage = function (e) {
                el.value += "接收消息:" + e.data + "\r\n";
            }
            wsClientSp2.onerror = function (e) {
                el.value += "连接失败!原因【" + JSON.stringify(e) + "】\r\n";
            }

            // 连接时需要发送该消息
            function connect() {
                console.log(1, wsClientSp2)
                if (wsClientSp2.readyState != 3) {
                    wsClientSp2.send(`{"protocol":"json","target":"GetDeviceHoles","arguments":[],"type":1,"version":1}${String.fromCharCode(0x1e)}`);
                }
                console.log(2, wsClientSp2)
            }

            function send() {
                wsClientSp2.send(`{"type":1,"target":"GetDeviceHoles","arguments":[]}${String.fromCharCode(0x1e)}`);
            }
        } catch (e) {
            console.log(e)
        }

    </script>
</body>

</html>

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值