Sends heartbeat message to Discord

        Attributes:
            ws: Websocket connection to discord
            seq: Sequence number of heartbeat
517174
def send(self, ws, seq):
        

        payload = {'op': 1, 'd': seq}
        payload = json.dumps(payload)
        logger.debug("Sending heartbeat with payload {}".format(payload))
        ws.send(payload)
        return
1210913
public function heartbeat()
    {
        $this->logger->debug('sending heartbeat', ['seq' => $this->seq]);

        $payload = [
            'op' => Op::OP_HEARTBEAT,
            'd'  => $this->seq,
        ];

        $this->send($payload);
        $this->heartbeatTime = microtime(true);
        $this->emit('heartbeat', [$this->seq, $this]);

        $this->heartbeatAckTimer = $this->loop->addTimer($this->heartbeatInterval / 1000, function () {
            if (! $this->connected) {
                return;
            }

            $this->logger->warning('did not receive heartbeat ACK within heartbeat interval, closing connection');
            $this->ws->close(1001, 'did not receive heartbeat ack');
        });
    }
381394
def heartbeat(self):
        
        pipeline = self.conn.pipeline()
        now = time.time()
        for replica in self.replicas:
            pipeline.zadd(self.key, '{start}:{name}'.format(
                start=replica[0],
                name=replica[1]
            ), now)
        ret = pipeline.execute()

        # Only notify the other nodes if we're not in the ring yet.
        if any(ret):
            self._notify()
1357534
def heartbeat(self):
        
        if self._rpc is not None and self._rpc.is_active:
            self._rpc.send(types.StreamingPullRequest())
171360
function wsConnect() {

            var typeOfConnection;

            if (location.protocol === 'https:') {
                typeOfConnection = 'wss';
            } else {
                typeOfConnection = 'ws'
            }

            self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);

            self.ws.onopen = function (event) {

                //send an intial message to server and prove that the connection is built.
                self.send('connected', 'WSM: Browser confirms websocket connection.')

                reactive(self);

            };

            self.ws.onmessage = function (event) {
                // flags.binary will be set if a binary data is received.
                // flags.masked will be set if the data was masked.
                //console.log(event.data);

                self.processMessage(JSON.parse(event.data));
            };

            self.ws.onclose = function (event) {

                wsConnect();
            }
        }
246604
function(opts) {
  opts = opts || {};
  this.heartbeat = null;
  this.timeout = null;
  this.disconnectOnTimeout = opts.disconnectOnTimeout;

  if(opts.heartbeat) {
    this.heartbeat = opts.heartbeat * 1000; // heartbeat interval
    this.timeout = opts.timeout * 1000 || this.heartbeat * 2;      // max heartbeat message timeout
    this.disconnectOnTimeout = true;
  }

  this.timeouts = {};
  this.clients = {};
}
613587
private void sendHeartbeat(Member target) {
        if (target == null) {
            return;
        }
        try {
            MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata();
            Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterClock.getClusterTime());
            op.setCallerUuid(clusterService.getThisUuid());
            node.nodeEngine.getOperationService().send(op, target.getAddress());
        } catch (Exception e) {
            if (logger.isFineEnabled()) {
                logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage()));
            }
        }
    }
750374
async def post_heartbeat(self, msg, _context):
        """"""

        name = msg.get('name')

        await self.service_manager.send_heartbeat(name)
550682
function sendHeartbeat() {
    _.forOwn(_this.socks, function (sock) {
      sock.write('hb');
    });
    setTimeout(sendHeartbeat, _this.heartbeatFreq);
  }
892469
protected void queueSendToWebsocketNB(String msg) {
        if (this.sendProcess.getPendingStepCount() < MAX_MSG_BACKLOG) {
            MySendStep sendStep = new MySendStep(msg);
            this.sendProcess.addStep(sendStep);
        } else {
            log.info("websocket backlog is full; aborting connection: sessionId={}", this.socketSessionId);

            this.safeClose();
        }
    }
591315
def heartbeat(time)
      RRRSpec.redis.setex(RRRSpec.make_key(key, 'heartbeat'), time, "alive")
      RRRSpec.redis.sadd(RRRSpec.make_key('rrrspec', 'worker'), key)
    end
1311505
def sendHeartbeat(self):
        
        for name, md in self.cfg.recordingDevices.items():
            try:
                data = marshal(md, recordingDeviceFields)
                data['serviceURL'] = self.cfg.getServiceURL() + API_PREFIX + '/devices/' + name
                targetURL = self.serverURL + API_PREFIX + '/devices/' + name
                logger.info("Pinging " + targetURL)
                resp = self.httpclient.put(targetURL, json=data)
                if resp.status_code != 200:
                    logger.warning("Unable to ping server at " + targetURL + " with " + str(data.keys()) +
                                   ", response is " + str(resp.status_code))
                else:
                    logger.info("Pinged server at " + targetURL + " with " + str(data.items()))
            except:
                logger.exception("Unable to ping server")
699989
def _authenticate_websocket(self, websocket, event_handler):
		
		log.debug('Authenticating websocket')
		json_data = json.dumps({
			"seq": 1,
			"action": "authentication_challenge",
			"data": {
				"token": self._token
			}
		}).encode('utf8')
		yield from websocket.send(json_data)
		while True:
			message = yield from websocket.recv()
			status = json.loads(message)
			log.debug(status)
			# We want to pass the events to the event_handler already
			# because the hello event could arrive before the authentication ok response
			yield from event_handler(message)
			if ('status' in status and status['status'] == 'OK') and \
					('seq_reply' in status and status['seq_reply'] == 1):
				log.info('Websocket authentification OK')
				return True
			elif 'seq_reply' in status and status['seq_reply'] == 1:
				log.error('Websocket authentification failed')
337144
public function handleWebSocketConnection(WebSocket $ws)
    {
        $this->logger->debug('connected to voice websocket');

        $resolver = (new DNSFactory())->createCached('8.8.8.8', $this->loop);
        $udpfac   = new DatagramFactory($this->loop, $resolver);

        $this->voiceWebsocket = $ws;

        $firstPack = true;
        $ip        = $port        = '';

        $discoverUdp = function ($message) use (&$ws, &$discoverUdp, $udpfac, &$firstPack, &$ip, &$port) {
            $data = json_decode($message->getPayload());

            if ($data->op == Op::VOICE_READY) {
                $ws->removeListener('message', $discoverUdp);

                $this->udpPort            = $data->d->port;
                $this->heartbeat_interval = $data->d->heartbeat_interval;
                $this->ssrc               = $data->d->ssrc;

                $this->logger->debug('received voice ready packet', ['data' => json_decode(json_encode($data->d), true)]);

                $this->send([
                    'op' => Op::VOICE_HEARTBEAT,
                    'd'  => microtime(true),
                ]);
                $this->emit('ws-heartbeat', []);

                $this->heartbeat = $this->loop->addPeriodicTimer($this->heartbeat_interval / 1000, function () {
                    $this->send([
                        'op' => Op::VOICE_HEARTBEAT,
                        'd'  => microtime(true),
                    ]);
                    $this->emit('ws-heartbeat', []);
                });

                $buffer = new Buffer(70);
                $buffer->writeUInt32BE($this->ssrc, 3);

                $udpfac->createClient("{$this->endpoint}:{$this->udpPort}")->then(function (Socket $client) use (&$ws, &$firstPack, &$ip, &$port, $buffer) {
                    $this->logger->debug('connected to voice UDP');
                    $this->client = $client;

                    $this->loop->addTimer(0.1, function () use (&$client, $buffer) {
                        $client->send((string) $buffer);
                    });

                    $this->udpHeartbeat = $this->loop->addPeriodicTimer(5, function () use ($client) {
                        $buffer = new Buffer(9);
                        $buffer[0] = pack('c', 0xC9);
                        $buffer->writeUInt64LE($this->heartbeatSeq, 1);
                        ++$this->heartbeatSeq;

                        $client->send((string) $buffer);
                        $this->emit('udp-heartbeat', []);
                    });

                    $client->on('error', function ($e) {
                        $this->emit('udp-error', [$e]);
                    });

                    $decodeUDP = function ($message) use (&$decodeUDP, $client, &$ip, &$port) {
                        $message = (string) $message;
                        // let's get our IP
                        $ip_start = 4;
                        $ip = substr($message, $ip_start);
                        $ip_end = strpos($ip, "\x00");
                        $ip = substr($ip, 0, $ip_end);

                        // now the port!
                        $port = substr($message, strlen($message) - 2);
                        $port = unpack('v', $port)[1];

                        $this->logger->debug('received our IP and port', ['ip' => $ip, 'port' => $port]);

                        $payload = [
                            'op' => Op::VOICE_SELECT_PROTO,
                            'd'  => [
                                'protocol' => 'udp',
                                'data'     => [
                                    'address' => $ip,
                                    'port'    => (int) $port,
                                    'mode'    => $this->mode,
                                ],
                            ],
                        ];

                        $this->send($payload);

                        $client->removeListener('message', $decodeUDP);

                        if (! $this->deaf) {
                            $client->on('message', [$this, 'handleAudioData']);
                        }
                    };

                    $client->on('message', $decodeUDP);
                }, function ($e) {
                    $this->logger->error('error while connecting to udp', ['e' => $e->getMessage()]);
                    $this->emit('error', [$e]);
                });
            }
        };

        $ws->on('message', $discoverUdp);
        $ws->on('message', function ($message) {
            $data = json_decode($message->getPayload());

            $this->emit('ws-message', [$message, $this]);

            switch ($data->op) {
                case Op::VOICE_HEARTBEAT: // keepalive response
                    $end = microtime(true);
                    $start = $data->d;
                    $diff = ($end - $start) * 1000;

                    if ($diff <= 10) { // set to 20ms
                        $this->setFrameSize(20);
                    } elseif ($diff <= 20) { // set to 40ms
                        $this->setFrameSize(40);
                    } else { // set to 60ms
                        $this->setFrameSize(60);
                    }

                    $this->emit('ws-ping', [$diff]);
                    break;
                case Op::VOICE_DESCRIPTION: // ready
                    $this->ready = true;
                    $this->mode = $data->d->mode;
                    $this->secret_key = '';

                    foreach ($data->d->secret_key as $part) {
                        $this->secret_key .= pack('C*', $part);
                    }

                    $this->logger->debug('received description packet, vc ready', ['data' => json_decode(json_encode($data->d), true)]);

                    if (! $this->reconnecting) {
                        $this->emit('ready', [$this]);
                    } else {
                        $this->reconnecting = false;
                        $this->emit('resumed', [$this]);
                    }

                    break;
                case Op::VOICE_SPEAKING: // user started speaking
                    $this->emit('speaking', [$data->d->speaking, $data->d->user_id, $this]);
                    $this->emit("speaking.{$data->d->user_id}", [$data->d->speaking, $this]);
                    $this->speakingStatus[$data->d->ssrc] = $data->d;
                    break;
            }
        });

        $ws->on('error', function ($e) {
            $this->logger->error('error with voice websocket', ['e' => $e->getMessage()]);
            $this->emit('ws-error', [$e]);
        });

        $ws->on('close', function ($op, $reason) {
            $this->logger->warning('voice websocket closed', ['op' => $op, 'reason' => $reason]);
            $this->emit('ws-close', [$op, $reason, $this]);
        });

        if (! $this->sentLoginFrame) {
            $payload = [
                'op' => Op::VOICE_IDENTIFY,
                'd'  => [
                    'server_id'  => $this->channel->guild_id,
                    'user_id'    => $this->data['user_id'],
                    'session_id' => $this->data['session'],
                    'token'      => $this->data['token'],
                ],
            ];

            $this->logger->debug('sending identify', ['packet' => $payload]);

            $this->send($payload);
            $this->sentLoginFrame = true;
        }
    }
699401
function send(id) {
        if (msg.ack) { server._rememberAck(msg.ack, ws.broker_uuid); }

        var destWs = server.id2ws[id];
        if (destWs) {
            if (destWs.readyState === WebSocket.OPEN) {
                destWs.send(JSON.stringify({
                    action: 'message',
                    message: msg.message,
                    ack: msg.ack,
                    from: server.ws2id[ws.broker_uuid]
                }));
            } else {
                err = new Error('Unable to send message. Client "'+id+'" disconnected');
                server.emit('error', err);
            }
        } else {
            server.emit('warn', new Error('Unable to send message. Client "'+id+'" unknown'));
        }
    }
990327
function Channel_sendMessage(message) {
  if (!this.wsConn) return
  if (!this.wsConn.connected) return

  DEBUGMSG("send: " + utils.JS(message))

  try {
    this.wsConn.sendUTF(JSON.stringify(message))
  }
  catch(e) {
    // occurs when socket closed, oh well
  }
}
553543
function startHeartbeats () {
    _isMaster = true
    if (_hearbeatInterval) return
    debug('starting heartbeats')
    _sendHeartbeat()
    _hearbeatInterval = setInterval(_sendHeartbeat, HEARTBEAT_INTERVAL)
  }