将 setInterval 与 socket.write 一起使用

Using setInterval with socket.write

这是有效的代码,但它只写入一次数据:

var net = require('net');
var PORT = 3000;
var client = new net.Socket();
client.connect(PORT, function(){
  client.write('{printing}');
})

我希望每隔几秒就写同样的东西。写了下面的代码,但它似乎不起作用:

client.connect(PORT, function(){
   setInterval(function(){
     client.write('{ printing }');
   },10000);
 })

以下是我不断收到的错误:

node:events:355
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:160:15)
    at writeGeneric (node:internal/stream_base_commons:151:3)
    at Socket._writeGeneric (node:net:773:11)
    at Socket._write (node:net:785:8)
    at writeOrBuffer (node:internal/streams/writable:395:12)
    at Socket.Writable.write (node:internal/streams/writable:340:10)
    at Timeout._onTimeout (/app/src/index.js:135:14)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:188:8)
    at emitErrorCloseNT (node:internal/streams/destroy:153:3)
    at processTicksAndRejections (node:internal/process/task_queues:81:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}
[nodemon] app crashed - waiting for file changes before starting..

我是这样修复的:

client.connect(PORT, function(){
    client.write('printing')
  })

  //adding drain if the buffer gets full
  client.on('drain',()=>{
    console.log("draining the buffer")
    setTimeout(() => {
        client.write('printing')
    })

    //reading the response recieved : ("ok")
  client.on('data', (data) => {})

  //in case of an error, closing the connection
  client.on('error',err => {}).on('close',() => {
    setTimeout(() => {
      client.connect(PORT, function(){
        client.write('printing')
  
      })
    },40000)
  })

在此上下文中,EPIPE 错误可能意味着您正在尝试写入已关闭的套接字。由于您显示的 setInterval() 示例一直持续下去,这可能意味着您最初连接的套接字在某个时候关闭,但您的 setInterval() 仍在触发并尝试写入它。

您不会在此处显示您要完成的任务的总体上下文以准确了解要建议的内容,但至少,您需要调用 clearInterval() 以在套接字出现时停止计时器它试图写入被关闭,无论是有意还是因为错误。

下面是一个示例,说明如果您遇到这种情况,您可以如何进行调试:

const net = require('net');
const PORT = 3000;
const client = new net.Socket();
let timer;

function disableTimer() {
   if (timer) {
       clearInterval(timer);
       timer = null;
   }
}

client.on('error', err => {
    console.log("socket error", err);
    disableTimer();
}).on('close', () => {
    console.log("socket closed");
    disableTimer();
});

client.connect(PORT, function(){
   timer = setInterval(function(){
     client.write('{ printing }');
   },10000);
});