node.js - handling TCP socket error ECONNREFUSED

后端 未结 2 1691
醉酒成梦
醉酒成梦 2021-02-02 10:39

I\'m using node.js with socket.io to give my web page access to character data served by a TCP socket. I\'m quite new to node.js.

User ---->

2条回答
  •  感情败类
    2021-02-02 11:03

    The only way I found to fix this is wrapping the net stuff in a domain:

    const domain = require('domain');
    const net = require('net');
    
    const d = domain.create();
    
    d.on('error', (domainErr) => {
        console.log(domainErr.message);
    });
    
    d.run(() => {
        const client = net.createConnection(options, () => {
    
            client.on('error', (err) => {
                throw err;
            });
            client.write(...);
            client.on('data', (data) => {
                ...
            });
        });
    });
    

    The domain error captures error conditions which arise before the net client has been created, such as an invalid host.

    See also: https://nodejs.org/api/domain.html

提交回复
热议问题