如何在Node.js套接字中接收超过1024个字节的数据?

时间:2018-10-24 11:41:47

标签: node.js sockets tcp

使用以下代码,我正在从设备接收数据。但是,如果设备发送的数据超过1024个字节,则多余的数据会被修剪掉,而我只接收1024个字节。如果有最大读取大小限制为1024字节,如何增加它?

我试图检查并增加当前缓冲区的大小

socket.bufferSize  // result is 0
socket.setBufferSize(8192); // error - setBufferSize is not a function

下面是用于接收数据的套接字代码。

'use strict';
import net from 'net';
let logger = require('./logger')(module);
/*
* Socket Server.
*/
const app = net.createServer(socketServer)
/**
* Socket Server Error.
*/
 .on('error', (error) => {
   if (error.code === 'EADDRINUSE') {
     /**
      * Address already in use.
      */
     logger.error(`port already in use: ${error}`);
   } else {
     /**
      * Other types of errors.
      */
     logger.error(`error in socket server: ${error}`);
   }
 })
 /**
  * Socket Server Close.
  */
 .on('close', () => {
   logger.error(`socket server closed`);
 });


function socketServer(socket) {

 /**
  * @param {Number} milli-seconds - Trigger 'timeout' event if TCP 
  *   Socket is idle for given time.
  */
 socket.setTimeout(config.tcp_timeout);
 // socket.setBufferSize(8192) // gives error

 /**
  * @param {Buffer} deviceData - Device Data in Buffer format.
  */
 socket.on('data', (deviceData) => {
     logger.debug(deviceData);
 });

 socket.on('drain', () => {
   /**
    * Trigger when socket.write is complete.
    */
   // [ TODO: findout when this is executed. ]
   logger.info(`socket write is succesful`);
 });

 socket.on('timeout', () => {
   /**
    * [TODO: step if connection is idle.]
    */
   logger.warn(`${socket.imei} is idle`);
   // socket.destroy();
 });
}

export default app;

0 个答案:

没有答案