node-ipc.js
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
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)); |