权限没有,则隐藏 function forum_list_access_filter($forumlist, $gid, $allow = 'allowread') { global $grouplist; if (empty($forumlist)) return array(); if (1 == $gid) return $forumlist; $forumlist_filter = $forumlist; $group = $grouplist[$gid]; foreach ($forumlist_filter as $fid => $forum) { if (empty($forum['accesson']) && empty($group[$allow]) || !empty($forum['accesson']) && empty($forum['accesslist'][$gid][$allow])) { unset($forumlist_filter[$fid]); } unset($forumlist_filter[$fid]['accesslist']); } return $forumlist_filter; } function forum_filter_moduid($moduids) { $moduids = trim($moduids); if (empty($moduids)) return ''; $arr = explode(',', $moduids); $r = array(); foreach ($arr as $_uid) { $_uid = intval($_uid); $_user = user_read($_uid); if (empty($_user)) continue; if ($_user['gid'] > 4) continue; $r[] = $_uid; } return implode(',', $r); } function forum_safe_info($forum) { //unset($forum['moduids']); return $forum; } function forum_filter($forumlist) { foreach ($forumlist as &$val) { unset($val['brief'], $val['announcement'], $val['seo_title'], $val['seo_keywords'], $val['create_date_fmt'], $val['icon_url'], $val['modlist']); } return $forumlist; } function forum_format_url($forum) { global $conf; if (0 == $forum['category']) { // 列表URL $url = url('list-' . $forum['fid'], '', FALSE); } elseif (1 == $forum['category']) { // 频道 $url = url('category-' . $forum['fid'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = url('read-' . trim($forum['brief']), '', FALSE); } if ($conf['url_rewrite_on'] > 1 && $forum['well_alias']) { if (0 == $forum['category'] || 1 == $forum['category']) { $url = url($forum['well_alias'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = ($forum['threads'] && $forum['brief']) ? url($forum['well_alias'] . '-' . trim($forum['brief']), '', FALSE) : url($forum['well_alias'], '', FALSE); } } return $url; } function well_forum_alias() { $forumlist = forum_list_cache(); if (empty($forumlist)) return ''; $key = 'forum-alias'; static $cache = array(); if (isset($cache[$key])) return $cache[$key]; $cache[$key] = array(); foreach ($forumlist as $val) { if ($val['well_alias']) $cache[$key][$val['fid']] = $val['well_alias']; } return array_flip($cache[$key]); } function well_forum_alias_cache() { global $conf; $key = 'forum-alias-cache'; static $cache = array(); // 用静态变量只能在当前 request 生命周期缓存,跨进程需要再加一层缓存:redis/memcached/xcache/apc if (isset($cache[$key])) return $cache[$key]; if ('mysql' == $conf['cache']['type']) { $arr = well_forum_alias(); } else { $arr = cache_get($key); if (NULL === $arr) { $arr = well_forum_alias(); !empty($arr) AND cache_set($key, $arr); } } $cache[$key] = empty($arr) ? '' : $arr; return $cache[$key]; } ?>javascript - websocket ping with node js - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - websocket ping with node js - Stack Overflow

programmeradmin9浏览0评论

I am learning on how to use websockets. I am returning data to the front-end from the server via normal ws.send but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.

ws.on('connection', function connection(ws, req) {

  ws.on('message', function ining(message) {
    return_data = message;
    heart_beat = {status:"Accepted", currentTime:"2013-02-01T20:53:32.486Z", "heartbeatInterval":300}

    ws.send(JSON.stringify(heart_beat));
    const interval = setInterval(function ping() {
    ws.clients.forEach(function each(ws) {
      if (ws.isAlive === false) return ws.terminate();

        ws.isAlive = false;
        ws.ping('', false, true);
      });
  }, 300);
  });
});

I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me

Here is my front-end code.

ws.onopen = function(){
    console.log("Connected");
}
ws.onclose = function(){
    console.log("Disconnected");
    ws.send('Disconnected');
}

Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.

I am learning on how to use websockets. I am returning data to the front-end from the server via normal ws.send but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.

ws.on('connection', function connection(ws, req) {

  ws.on('message', function ining(message) {
    return_data = message;
    heart_beat = {status:"Accepted", currentTime:"2013-02-01T20:53:32.486Z", "heartbeatInterval":300}

    ws.send(JSON.stringify(heart_beat));
    const interval = setInterval(function ping() {
    ws.clients.forEach(function each(ws) {
      if (ws.isAlive === false) return ws.terminate();

        ws.isAlive = false;
        ws.ping('', false, true);
      });
  }, 300);
  });
});

I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me

Here is my front-end code.

ws.onopen = function(){
    console.log("Connected");
}
ws.onclose = function(){
    console.log("Disconnected");
    ws.send('Disconnected');
}

Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.

Share Improve this question asked Oct 15, 2017 at 13:23 Masnad NihitMasnad Nihit 1,9962 gold badges22 silver badges41 bronze badges 15
  • What do you mean by client are still alive ? – user2652134 Commented Oct 15, 2017 at 13:28
  • @BrahmaDev Client ( in the browser ) - if they close the browser they are gone, thats what I meant. – Masnad Nihit Commented Oct 15, 2017 at 13:30
  • If they close the browser, the websocket connection is gone too. You should no longer find them in ws.clients. – user2652134 Commented Oct 15, 2017 at 13:37
  • @BrahmaDev Not always, I want to use ping messages as a means to verify that the remote endpoint is still responsive. Even in the websocket repo in github they said it and I copied this example from there as well – Masnad Nihit Commented Oct 15, 2017 at 13:39
  • Can you please point me to that. This is new to me. – user2652134 Commented Oct 15, 2017 at 13:41
 |  Show 10 more ments

1 Answer 1

Reset to default 3

You have to clear the Timeout with clearInterval

Here is a working example with uWebSocket :

'use strict';

const uws = require('uws');

const PORT = 3000


/*********************************************************************
*                               Server                               *
*********************************************************************/

var wsServer = new uws.Server({ 'port': PORT });

let nextId=1;

wsServer.on('connection', function(ws) {
    console.log('connection !');

    ws.id='cnx'+nextId++;

    ws.on('message', function(mess){console.log('message : '+mess); });

    ws.on('error', function(error) {
        console.log('Cannot start server');
    });

    ws.on('close', function(code, message) {
            console.log('Disconnection: ' + code + ', ' + message);
            clearInterval(ws.timer);
            });

    ws.on('pong',function(mess) { console.log(ws.id+' receive a pong : '+mess); });

    ws.timer=setInterval(function(){pingpong(ws);},1000);

});

function pingpong(ws) {
    console.log(ws.id+' send a ping');
    ws.ping('coucou',{},true);
} // end of pingpong


/*********************************************************************
*                               Client                               *
*********************************************************************/

var wsClient1 = createClient('client1');
var wsClient2 = createClient('client2');

function createClient(id) {
    var client = new uws('ws://localhost:'+PORT);
    client.id=id;
    client.on('ping',function(mess){ console.log(this.id+' receive a ping : '+mess); } );
    client.on('message',function(mess){ console.log(this.id+' receive a message : '+mess); } );
    client.on('close',function(){ console.log(this.id+' closed'); } );
    return client;
}

function closeClient(client) {
    console.log('close '+client.id); client.close();
}

setTimeout(function(){ closeClient(wsClient1); closeClient(wsClient2); wsServer.close(); },2500);

output is :

connection !
connection !
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
close client1
close client2
client1 closed
client2 closed
Disconnection: 0,
Disconnection: 0,
发布评论

评论列表(0)

  1. 暂无评论