Last active
November 28, 2020 21:47
-
-
Save badsyntax/708e50315e1621c68544dae354af5afe to your computer and use it in GitHub Desktop.
Super simple Node.js IPC with Unix domain sockets
This file contains hidden or 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
const net = require('net'); | |
const socketPath = '/tmp/my.unix.sock'; | |
const server = net | |
.createServer() | |
.on('connection', (stream) => { | |
console.log('Server: client connected'); | |
stream.setEncoding('utf-8'); | |
stream.on('end', () => { | |
console.log('Server: client disconnected'); | |
}); | |
stream.on('data', (msg) => { | |
console.log('Server: got client message:', msg); | |
if (msg === 'command') { | |
stream.write('command response'); | |
} | |
}); | |
}) | |
.on('close', () => { | |
console.log('Server: shut down'); | |
}) | |
.listen(socketPath, () => { | |
console.log('Server bound to socket at path:', socketPath); | |
}); | |
const client = net.createConnection(socketPath); | |
client | |
.setEncoding('utf-8') | |
.on('connect', () => { | |
console.log('Client: connected to server'); | |
client.write('command'); | |
client.end(); | |
server.close(); | |
}) | |
.on('data', (data) => { | |
console.log('Client: got server message:', data); | |
}) | |
.on('end', () => { | |
console.log('Client: disconnected'); | |
}) | |
.on('error', (data) => console.error(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment