Created
January 15, 2021 13:34
-
-
Save uzuki-P/a941a8c316d629dfcd1923967d8cd1c5 to your computer and use it in GitHub Desktop.
NodeJs - Socket connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var net = require('net'); | |
var server = net.createServer(function(c) { //'connection' listener | |
console.log('server connected'); | |
c.on('end', function() { | |
console.log('server disconnected'); | |
}); | |
c.write('hello\r\n'); | |
c.pipe(c); | |
}); | |
server.on('error', function (e) { | |
if (e.code == 'EADDRINUSE') { | |
var clientSocket = new net.Socket(); | |
clientSocket.on('error', function(e) { // handle error trying to talk to server | |
if (e.code == 'ECONNREFUSED') { // No other server listening | |
fs.unlinkSync('/tmp/app-monitor.sock'); | |
server.listen('/tmp/app-monitor.sock', function() { //'listening' listener | |
console.log('server recovered'); | |
}); | |
} | |
}); | |
clientSocket.connect({path: '/tmp/app-monitor.sock'}, function() { | |
console.log('Server running, giving up...'); | |
process.exit(); | |
}); | |
} | |
}); | |
server.listen('/tmp/app-monitor.sock', function() { //'listening' listener | |
console.log('server bound'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from this stackoverflow