websocket报错

发布于 2022-09-04 20:08:52 字数 2357 浏览 8 评论 0

连接服务器时报了上面错误,请问是服务器问题还是浏览器问题?

clipboard.png

客户端代码
$(document).ready(function(){

//显示信息
var log = function(s) {
    if (document.readyState !== "complete") {
        log.buffer.push(s);
    } else {
        document.getElementById("output").textContent += (s + "\n");
        document.getElementById("outputdiv").scrollTop = document.getElementById("outputdiv").scrollHeight;
    }
};
log.buffer = [];
//显示连接状态
function setConnected(status) {
    document.getElementById("socketstatus").innerHTML = status;
}
var ws = null;

//连接
function connect() {
    if (ws != null) {
        log("现已连接");
        return ;
    }
    url = "ws://120.27.37.203:80";
    // url = "ws://localhost:8080";
    if ('WebSocket' in window) {
        ws = new WebSocket(url);
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(url);
    } else {
        alert("您的浏览器不支持WebSocket。");
        return ;
    }
    console.log(ws);
    ws.binaryType = "arraybuffer";
    ws.protocol = 1;
    ws.onopen = function() {
        log("open");
        setConnected("已连接");
        //设置发信息送类型为:ArrayBuffer
        ws.binaryType = "arraybuffer";
        //发送一个字符串和一个二进制信息
        ws.send("thank you for accepting this WebSocket request");
        var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]);
        ws.send(a.buffer);
    };
    ws.onmessage = function(e) {
        log(e.data.toString());
    };
    ws.onclose = function(e) {
        log("closed");
    };
    ws.onerror = function(e) {
        // log("error");
        console.log(ws);
        console.log(e)
    }
}
//断开连接
function disconnect() {
    if (ws != null) {
        ws.close();
        ws = null;
        setConnected("已断开");
    }
}
window.onload = function() {
    connect();
    log(log.buffer.join("\n"));
    //发送页面上输入框的信息
    document.getElementById("sendButton").onclick = function() {
        if (ws != null) {
            ws.send(document.getElementById("inputMessage").value);
        }
    };
    //停止心跳信息
    document.getElementById("stopButton").onclick = function() {
        if (ws != null) {
            var a = new Uint8Array([1, 9, 2, 0, 1, 5, 1, 6]);
            ws.send(a.buffer);
        }
    }
}

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回眸一笑 2022-09-11 20:08:52

从表现来看是服务端的问题,在握手阶段就报错了。看下是不是服务端对websocket的支持有问题。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文