使用socket.io在两个不同页面之间进行通信?

时间:2017-10-24 20:25:16

标签: javascript jquery html socket.io

当用户按下页面A.html上的按钮时,我正试图这样做,它将使用socket.io(托管在同一个网络服务器上)动态更改页面B.html上的图像。是否可以添加故意延迟,例如setTimeout()?

1 个答案:

答案 0 :(得分:0)

  

是否可以添加故意延迟,例如setTimeout()?

是的,可以在客户端或服务器中添加延迟。例如,在页面A客户端:

// after one second delay, send the message to the server
setTimeout(function() {
    socket.emit("changeImage", "pageB");
}, 1000);

或者,在服务器上:

socket.on("changeImage", function(data) {
    if (data === "pageB") {
        setTimeout(function() {
            socket.emit("changeImageB", "pageB");
        }, 1000);
    }
});

甚至在pageB客户端中:

// listen for message to change the image
socket.on("changeImageB", function(data) {
    setTimeout(function() {
        // change image in the DOM here
    }, 1000);

});