tcp 收发数据demo(带粘包处理解决方案)

737 阅读1分钟
原文链接: cnodejs.org

项目地址: github.com/lvgithub/st… 进入example目录,1、运行server.js 2、运行client.js即可测试demo

server

const net = require('net')
const stick_package = require('../index')

let tcp_server = net.createServer(function (socket) {
    socket.stick = new stick_package(1024).setReadIntBE('32')
    socket.on('data', function (data) {
        socket.stick.putData(data)
    })

    socket.stick.onData(function (data) {
        // 解析包头长度
        let head = new Buffer(4)
        data.copy(head, 0, 0, 4)

        // 解析数据包内容
        let body = new Buffer(head.readInt32BE())
        data.copy(body, 0, 4, head.readInt32BE())

        console.log('data length: ' + head.readInt32BE())
        console.log('body content: ' + body.toString())
    })

    socket.stick.onError(function (error) {
        console.log('stick data error:' + error)
    })

    socket.on('close', function (err) {
        console.log('client disconnected')
    })
})

tcp_server.on('error', function (err) {
    throw err
})
tcp_server.listen(8080, function () {
    console.log('tcp_server listening on 8080')
})

client

const net = require('net')

const client = net.createConnection({ port: 8080, host: '127.0.0.1' }, function () {
    let body = Buffer.from('username=123&password=1234567,qwe')

    // 写入包头
    let headBuf = new Buffer(4)
    headBuf.writeUInt32BE(body.byteLength, 0)
    console.log('data length: ' + headBuf.readInt32BE())

    // 发送包头
    client.write(headBuf)
    // 发送包内容
    client.write(body)
    console.log('data body: ' + body.toString())

})

client.on('data', function (data) {
    console.log(data.toString())
})
client.on('end', function () {
    console.log('disconnect from server')
})