当我打开新窗口时,socket.io 得到不好的响应
Posted
技术标签:
【中文标题】当我打开新窗口时,socket.io 得到不好的响应【英文标题】:socket.io get bad response when I open new window 【发布时间】:2020-03-03 00:54:49 【问题描述】:我正在构建一个使用 socket.io 和 web worker api 每秒从服务器获取更新的 web 应用程序。其中一个按钮正在打开一个新窗口,当打开新窗口时,socket.io 停止工作并获得错误的请求响应
//part of the code
var socket = io(transports: ['polling']);
worker = new Worker("web_worker.js");
worker.onmessage = function(event)
socket.emit("check_for_updates");
//this function is called when a button is pressed
function new_window(client)
var uid = client.uid;
var new_window = window.open("/new?uid="+uid);
控制台中显示的错误:
polling-xhr.js:270 GET http://localhost/socket.io/?EIO=3&transport=polling&t=Mv0tQCC&sid=LnzFU8ClZrY0NHK5AA-r 400(错误请求)
polling-xhr.js:270 POST http://localhost/socket.io/?EIO=3&transport=polling&t=Mv0tQC-&sid=LnzFU8ClZrY0NHK5AA-r 400(错误请求)
【问题讨论】:
【参考方案1】:所以我设法解决了问题-问题是在新窗口中我使用默认设置打开了一个新套接字,这导致第一个套接字崩溃。我的解决方案是使用 Sockt.io 码头的命名空间-
服务器端:
var main_socket = io(http);
socket = main_socket.of('/first');
socket.once("connection", (socket) =>
console.log("user connected");
socket.on("disconnect", function()
console.log("user disconnected");
);
var second_socket = main_socket.of('/second');
second_socket.once("connection", (second_socket) =>
console.log("second connection");
客户端:
//part of the code
var socket = io(nsp="/first",Option=transports: ['polling']);
worker = new Worker("web_worker.js");
worker.onmessage = function(event)
socket.emit("check_for_updates");
//this function is called when a button is pressed
function new_window(client)
var socket = io(nsp="/second",Option=transports: ['polling']);
var uid = client.uid;
var new_window = window.open("/new?uid="+uid);
希望以后能帮到别人
【讨论】:
以上是关于当我打开新窗口时,socket.io 得到不好的响应的主要内容,如果未能解决你的问题,请参考以下文章
我怎样才能得到一个 socket.username ? (socket.io)