我在javascript中使用websocket。但是连接在一分钟后就关闭了。
我想知道一些事情:
1- Websocket不是自然地提供了乒乓信息来不关闭连接吗?我觉得必须这样。否则,websocket和TCP连接之间有什么区别?
2-如果我必须发送乒乓信息,那么ping消息是如何发送的?我需要做什么?WebSocket对象是否提供了ping方法?还是应该将方法称为websocket.send("ping")?我在javascipt中使用了自然的WebSocket对象。
3-服务器是否应对乒乓请求作出响应?这应该在服务器端单独实现吗?
注意:对不起,我的英语。
发布于 2018-06-15 22:56:37
此时,心跳通常是在服务器端实现的:从客户端可以做的事情不多。
但是,如果服务器一直关闭套接字连接,而您无法控制它,客户端就有可能在间隔内将任意数据发送到websocket:
let socket = null;
function connect_socket() {
socket = new WebSocket(ws_url);
socket.on("close", connect_socket); // <- rise from your grave!
heartbeat();
}
function heartbeat() {
if (!socket) return;
if (socket.readyState !== 1) return;
socket.send("heartbeat");
setTimeout(heartbeat, 500);
}
connect_socket();我强烈建议您尝试整理服务器端正在发生的事情,而不是试图在客户机上绕过它。
发布于 2018-06-15 13:45:05
是的,websockets中有乒乓帧。下面是一个使用ws模块的示例,其中服务器正在启动ping请求:
const http = require('http');
const ws = require('ws');
const server = http.createServer(function(req_stream_in, res_stream_out) {
// handle regular HTTP requests here
});
const webSocketServer = new ws.Server({
path: "/websocket",
server: server
});
const connected_clients = new Map();
webSocketServer.on('connection', function connection(ws_client_stream) {
// NOTE: only for demonstration, will cause collisions. Use a UUID or some other identifier that's actually unique.
const this_stream_id = Array.from(connected_clients.values()).length;
// Keep track of the stream, so that we can send all of them messages.
connected_clients.set(this_stream_id, ws_client_stream);
// Attach event handler to mark this client as alive when pinged.
ws_client_stream.is_alive = true;
ws_client_stream.on('pong', () => { ws_client_stream.is_alive = true; });
// When the stream is closed, clean up the stream reference.
ws_client_stream.on('close', function() {
connected_clients.delete(this_stream_id);
});
});
setInterval(function ping() {
Array.from(connected_clients.values()).forEach(function each(client_stream) {
if (!client_stream.is_alive) { client_stream.terminate(); return; }
client_stream.is_alive = false;
client_stream.ping();
});
}, 1000);发布于 2019-07-31 13:51:45
Mozilla记录了一项专门的乒乓球会议。
在握手之后的任何时候,客户端或服务器都可以选择向另一方发送ping。当接收到ping时,接收方必须尽快送回一个乒乓。例如,您可以使用它来确保客户机仍然是连接的。 乒乓球只是一个普通的框架,但它是一个控制框架。Pings的操作码为0x9,而pongs的操作码为0xA。当您得到ping时,用与ping完全相同的有效载荷数据返回一个乒乓(对于pings和pongs,最大有效负载长度为125)。您也可能得到一个乒乓而不发送ping;如果发生这种情况,请忽略它。 如果你在有机会投球之前得到了一个以上的乒乓球,你只会送一个乒乓球。
请参阅:WebSockets
在浏览器端可以找到更多关于ping/pong的深入讨论:从浏览器发送websocket ping/pong帧
更具体地说,阅读Websocket RFC 6455关于ping/pong的内容。
https://stackoverflow.com/questions/50876766
复制相似问题