Socket.io客户端由于ping超时/传输关闭而断开连接

时间:2018-06-29 14:10:16

标签: javascript python node.js sockets socket.io

这是我的设置:

Raspberry Pi 2(192.168.1.101):

  • 传感器记录温度,压力和湿度。
  • Python3脚本连接到Raspberry Pi 3,每5秒钟读取一次传感器数据并以JSON格式发送到Pi 3。

Raspberry Pi 3(192.168.1.100):

  • Node.js服务器在端口8888上侦听python客户端。
  • Socket.io在端口3000上侦听Web客户端(我的路由器上已打开端口3000和80)。
  • 具有显示传感器数据的网站的Web服务器(在端口80上)。
  • JavaScript使用foobar.ddns.net:3000使用socket.io连接到节点服务器。

其他:

  • 我正在使用noip.com来为我的动态IP地址提供域,我的路由器会在我的公共IP更改时通知noip。我有一个看起来像foobar.ddns.net的URL。

此设置似乎正在运行。 Python脚本正在将数据发送到节点服务器,该节点服务器将其转发到已连接的任何Web客户端,该客户端在网站上正确显示。

我的问题是,客户端和节点服务器之间经过一轮ping / pong之后,Web客户端断开了连接。

这是连接到服务器并接收数据时的chrome控制台日志: chrome console log

Web客户端连接,接收一些数据,与服务器进行ping / pong操作,接收更多数据,然后在应该再次ping / pong时断开连接,然后尝试重新连接一段时间后,循环继续。

这是node.js日志:
node.js server log

第一个新连接是Python客户端(我不确定为什么IP是Pi3地址),其余的是同一Web客户端连接,由于ping超时而断开连接,然后重新连接。客户端似乎基于服务器pingInterval + pingTimeout值而断开连接。

更改pingTimeout和pingInterval值只会延迟断开连接。

这是我的代码:

Python客户端:

import json
import socket
import bme280_sensor
import time
import os

class Connection():

    def __init__(self, host, port):
        self.host = host
        self.port = port

    def connect(self):
        print('Creating socket')
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as msg:
            print('Failed to create socket: %s' % msg)
            raise

        print('Socket created')

        server_address = (self.host, self.port)
        print('Connecting to %s:%s' % server_address)

        try:
            self.sock.connect(server_address)
        except socket.error as msg:
            print('Failed to connect: %s' % msg)
            raise

        print('Connected')

    def shutdown(self):
        print('Shutting down')
        self.sock.shutdown(socket.SHUT_RDWR)
        self.sock.close()

def measure_temp():
    bme_data = bme280_sensor.read_all()
    obj = {}
    obj['temp'] = round(bme_data[2], 2)
    obj['humidity'] = round(bme_data[0], 2)
    obj['pressure'] = round(bme_data[1], 2)
    return json.dumps(obj)

def sendData(sock):
    print('Sending data')
    while True:
        try:
            data = 'data,' + measure_temp()
            sock.sendall(data.encode())
        except socket.error as msg:
            print("Cannot send to server: %s" % msg)
            break

        time.sleep(5)

connection = Connection('192.168.1.100', 8888)

while True:
    try:
        connection.connect()
        sendData(connection.sock)
        connection.shutdown()
        break
    except socket.error as msg:
        print('Connection failed, retrying in 3 seconds.')
        time.sleep(3)

print('Done')

Node.js服务器:

var net = require('net');

var port = 8888;
var server = net.createServer();

// socket io listens for clients on port 3000
var io = require('socket.io')(3000,{
    pingInterval: 10000,
    pingTimeout: 5000,
});

// server listens for python client on port 8888
server.listen(port);

console.log('Server started');

// store the last data recorded, so when a socket.io client connects, they can get the last reading instead of waiting for the next one
global.last;

server.on('connection', function(socket){

    console.log('New server connection ' + socket.address().address);

    // when the server recieves data, send it to the connected socket clients
    socket.on('data', function(data){

        // strip the first 5 characters from the input string, parse json from the result
        var actual = generateJSON(data.toString().substring(5));
        // store the dta
        global.last = actual;

        //send the data
        io.sockets.emit('data', actual);
    });

});

io.on('connection', function(socket){

    console.log('New io connection ' + socket.id);

    // if the server has data previously recorded, send it to the new client
    if(global.last){
        io.emit('data', global.last);
    }

    socket.on('disconnect', function(reason){
        console.log('io disconnect: ' + reason);
    });
});

function generateJSON(data){
    var dataJSON = JSON.parse(data);
    var obj = new Object();

    obj.temperature = dataJSON.temp;
    obj.humidity = dataJSON.humidity;
    obj.pressure = dataJSON.pressure;
    obj.datetime = new Date().toString();

    return JSON.stringify(obj);
}

网站Javascript:

var socket;
var connected = false;

function connect(){
    console.log('connecting...')

    if(socket){
        socket.destroy()
        delete socket;
        socket = null;
    }

    socket = io.connect("http://foobar.ddns.net:3000", {
        forceNew: true,
        reconnection: true,
        reconnectionDelay: 3000,
        reconnectionDelayMax: 5000,
        reconnectionAttempts: Infinity
    });

    console.log(socket);

    socket.on("data", function(data){
        var obj = JSON.parse(data);
        console.log(data);

        $('#temperature-value').text(obj.temperature);
        $('#humidity-value').text(obj.humidity);
        $('#pressure-value').text(obj.pressure);
        lastUpdate = new Date();
    });

    socket.on('connect_error', function(error){
        console.log('connection error: ' + error);
    }); 

    socket.on('connect_timeout', function(){
        console.log('connection timeout');
    });

    socket.on('reconnect', function(){
        console.log('reconnect');
    });

    socket.on('reconnect_attempt', function(){
        console.log('reconnect attempt');
    });

    socket.on('reconnect_failed', function(){
        console.log('reconnect_failed');
    });

    socket.on('reconnect_error', function(){
        console.log('reconnect_error');
    });

    socket.on('reconnecting', function(){
        console.log('reconnecting');
    });

    socket.on('ping', function(){
        console.log('ping');
    });

    socket.on('pong', function(ms){
        console.log('pong ' + ms + "ms");
    });

    socket.on('connect', function(){
        console.log('connected to server');
        connected = true;
    });

    socket.on('disconnect', function(reason){
        console.log('disconnected from server: ' + reason);
        connected = false;
    });
}

$(document).ready(function(){
    connect();
});

我正在index.html中访问socket.io.js脚本:
<script src="http://foobar.ddns.net:3000/socket.io/socket.io.js"></script>

这是功能正常,但断开连接很烦人,我希望客户端保持连接状态。我感觉到我的node.js服务器未正确安装,但是我无法弄清楚问题出在哪里。如果有更好的方式从python脚本> node.js服务器>网络客户端中馈送数据,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题!它与node.js或socket.io无关。

问题出在显示数据的网页上,我有这种方法可以更新显示自上次更新以来的秒数的跨度:

function updateLastUpdateTimer(){
    var seconds = (new Date() - lastUpdate) / 1000;

    $('#time-since-last-update').text(formatTime(seconds) + " ago");
    $('#last-updated-time').text(lastUpdate);
    setInterval(updateLastUpdateTimer, 1000);
}

应该是setInterval的问题是setTimeout。我意识到我的网页正在耗尽RAM,这导致客户端套接字挂起并且没有向服务器发送任何数据,这导致了超时!

setInterval方法每x毫秒运行一次函数。不要将其放在您要调用的方法中!只需调用一次即可。

对于任何阅读此文章的人来说,它们在ping超时和传输关闭方面都存在相同的问题,请检查您的客户端!

相关问题