const net = require('net');
const path = require('path');
const fs = require('fs');
const os = require('os');
// Create a temporary directory for IPC socket
const tmpDir = os.tmpdir();
const sockPath = path.join(tmpDir, 'node-ipc-example.sock');
// Clean up any existing socket file
if (fs.existsSync(sockPath)) {
console.log('Removing existing socket file');
fs.unlinkSync(sockPath);
}
// Create an IPC server
const server = net.createServer((socket) => {
console.log('IPC Server: Client connected');
// Set encoding for the socket
socket.setEncoding('utf8');
// Handle data from client
socket.on('data', (data) => {
console.log(`IPC Server received: ${data.trim()}`);
// Send a response
const response = `Processed: ${data.trim().toUpperCase()}`;
console.log(`IPC Server sending: ${response}`);
socket.write(response);
});
// Handle client disconnection
socket.on('end', () => {
console.log('IPC Server: Client disconnected');
});
// Handle errors
socket.on('error', (err) => {
console.error('IPC Server socket error:', err.message);
});
});
// Handle server errors
server.on('error', (err) => {
console.error('IPC Server error:', err.message);
// Try to clean up the socket file
if (fs.existsSync(sockPath)) {
try {
fs.unlinkSync(sockPath);
} catch (e) {
console.error('Failed to clean up socket file:', e.message);
}
}
});
// Start the IPC server
server.listen(sockPath, () => {
console.log(`IPC Server listening on ${sockPath}`);
// Start a client to test the IPC connection
startIPCClient();
});
// Function to start the IPC client
function startIPCClient() {
console.log('Starting IPC client...');
// Create a client connection to the IPC server
const client = net.createConnection({ path: sockPath }, () => {
console.log('IPC Client: Connected to server');
// Send some test messages
const messages = [
'Hello, IPC Server!',
'This is a test message',
'Another message',
'QUIT'
];
let index = 0;
// Function to send the next message
const sendNext = () => {
if (index < messages.length) {
const msg = messages[index++];
console.log(`IPC Client sending: ${msg}`);
client.write(msg + '\n');
} else {
client.end();
}
};
// Handle responses from server
let buffer = '';
client.on('data', (data) => {
buffer += data.toString();
// Split by newlines to handle multi-line responses
const lines = buffer.split('\n');
buffer = lines.pop(); // Keep the last incomplete line in the buffer
// Process complete lines
for (const line of lines) {
if (line) { // Skip empty lines
console.log(`IPC Client received: ${line}`);
// If this was a response to QUIT, end the connection
if (line.includes('QUIT')) {
client.end();
return;
}
// Send the next message after a short delay
setTimeout(sendNext, 500);
}
}
});
// Start sending messages
sendNext();
});
// Handle connection close
client.on('close', () => {
console.log('IPC Client: Connection closed');
// Close the server after a short delay
setTimeout(() => {
server.close(() => {
console.log('IPC Server closed');
// Clean up the socket file
if (fs.existsSync(sockPath)) {
try {
fs.unlinkSync(sockPath);
console.log('Removed socket file');
} catch (e) {
console.error('Failed to remove socket file:', e.message);
}
}
});
}, 1000);
});
// Handle connection errors
client.on('error', (err) => {
console.error('IPC Client error:', err.message);
// Try to close the server
if (server.listening) {
server.close();
}
});
}
// Handle process termination
process.on('SIGINT', () => {
console.log('\nCaught interrupt signal');
// Close the server
if (server.listening) {
server.close(() => {
// Clean up the socket file
if (fs.existsSync(sockPath)) {
try {
fs.unlinkSync(sockPath);
console.log('Removed socket file');
} catch (e) {
console.error('Failed to remove socket file:', e.message);
}
}
process.exit(0);
});
} else {
process.exit(0);
}
});