gpt4 book ai didi

javascript - 无法使用javascript连接网络套接字

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:31 25 4
gpt4 key购买 nike

我想连接到我的 web 套接字,它使用一些 ip 放在 amazone 实例上。我可以将我的网络套接字与一些 ip 和端口连接到 google rest 客户端应用程序并且它工作得很好。截屏 : enter image description here

但是如果我想用 java 脚本连接它,它就无法连接。这在 2-3 个月前工作正常。我没有改变和事情,但它现在不工作。如果我想连接 firefox,它会产生错误。这是我的代码:-

function init() {
var host = "ws://XX.XX.XXX.XXX:XXXX"; // SET THIS TO YOUR SERVER


try {
var socket = new WebSocket(host);
// alert('WebSocket - status ' + socket.readyState);
log('WebSocket - status ' + socket.readyState);

socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);
log("Welcome - status " + this.readyState);

if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
// alert("Received: " + msg.data);
log("Received: " + msg.data);

};
socket.onclose = function (msg) {
// alert("Disconnected - status " + this.readyState);
log("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);
log(ex);
}
$("msg").focus();
}

这是警报状态 0 并且错误显示在控制台中:-

Firefox can't establish a connection to the server at ws://XX.XX.XXX.XXX:XXXX.


var socket = new WebSocket(host);

最佳答案

我会尝试你的代码,对我来说工作得很好,我会用这个网页测试它:https://www.websocket.org/echo.html ,也许有助于测试目的。但我也发现了这个问题:websocket-rails, websocket handshake error ,也许也有帮助。但是我只是将您代码中的主机更改为:“ws://echo.websocket.org”,并且一切正常。希望您找到解决方案并且此信息对您有所帮助。这是我用于测试的代码:

function init() {
var host = "ws://echo.websocket.org";
try {
var socket = new WebSocket(host);
alert('WebSocket - status ' + socket.readyState);
socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);

if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
alert("Received: " + msg.data);
};
socket.onclose = function (msg) {
alert("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);

}
$("msg").focus();
}

*抱歉我的英语不好。

关于javascript - 无法使用javascript连接网络套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com