TCP客户端/服务器丢包

时间:2014-09-12 15:54:45

标签: node.js

我目前正在NodeJS中开发TCP客户端和服务器。 但为什么我有一个"丢包"这里? 查看屏幕截图:http://i.imgur.com/YoCtAAV.png

客户代码:

console.log('Starting Client...')

var net = require('net')

var client = new net.Socket()

client.connect(3000, '127.0.0.1', function() {
    console.log('Connected to server on 127.0.0.1:3000')

    var packet
    for (i = 0; i <= 20; i++) {
        packet = new Buffer(4)
        packet.writeUInt32LE(i, 0)
        client.write(packet)

        console.log('Packet Counter sent: ' + i)
    }
})

client.on('error', function(e) {
    if(e.code == 'ECONNRESET') {
        console.error('Connection abnormally closed')
    } else if(e.code == 'ECONNREFUSED') {
        console.error('Connection refused. Server down?')
    } else {
        console.error('Unhandled error occured:')
        console.error(e)
    }
})

client.on('close', function() {
    console.log('Connection closed')
})

服务器代码:

console.log('Starting Server...')

var net = require('net')

var server = net.createServer(function(session) {
    console.log('Connection opened')

    session.on('data', function(packet) {
        var packet_counter = packet.readUInt32LE(0)

        console.log('Packet Counter received: ' + packet_counter)
    })

    session.on('error', function(e) {
        if(e.code == 'ECONNRESET') {
            console.log('Connection closed')
        } else {
            console.error('Unhandled session error occured:')
            console.error(e)
        }
    })

    session.on('end', function() {
        console.log('Connection closed')
    })
})

server.on('error', function(e) {
    if(e.code == 'EADDRINUSE') {
        console.error('Port 3000 already in use')
    } else {
        console.error('Unhandled server error occured:')
        console.error(e)
    }
})

server.listen(3000, '0.0.0.0')

console.log('Server started on 0.0.0.0:3000')

如何解决此问题并在服务器日志中获得预期的输出?

Packet Counter received: 0
Packet Counter received: 1
Packet Counter received: 2
Packet Counter received: 3
Packet Counter received: 4
Packet Counter received: 5
Packet Counter received: 6
Packet Counter received: 7
Packet Counter received: 8
Packet Counter received: 9
Packet Counter received: 10
Packet Counter received: 11
Packet Counter received: 12
Packet Counter received: 13
Packet Counter received: 14
Packet Counter received: 15
Packet Counter received: 16
Packet Counter received: 17
Packet Counter received: 18
Packet Counter received: 19
Packet Counter received: 20

1 个答案:

答案 0 :(得分:0)

可能没有数据包丢失。 TCP只是不像你期望的那样发送数据包。它发送一个流 - 就像一个文件。文件不是由数据包组成的,而是由字节组成。 TCP模拟此行为。因此,当您发送两个“数据包”时,TCP层(您的TCP库,或操作系统或您的路由器或您的ISP)可能会将它们合并为一个TCP数据包或将它们分成多个TCP数据包。

要真正知道是否存在数据包丢失,您必须检查接收数据的总大小与发送数据的总大小。

这种类似文件流的行为是人们创建更高层协议(如HTTP或FTP或Bittorrent)的原因,用于编码数据包开始和结束的位置。

TCP不会为你做这件事。