如何通过IP地址与Socket远程通信?Electron/Node.js开发求助
Hey there! Since you're already able to pull IP and MAC addresses of devices on your network, you're already ahead of the curve—nice work so far! Let's walk through practical, actionable ways to implement bidirectional message communication between your Electron app and those remote PCs.
Since you're working within a local network, raw TCP or UDP is one of the most straightforward options. Node.js (and by extension Electron) has built-in modules for this, so no extra dependencies are needed for the basics.
Step 1: Run a Lightweight Service on Remote PCs
Each PC you want to control needs a small background service listening for incoming connections. Here's a simple TCP server example using Node.js's net module:
// Remote PC service code (can be packaged as a desktop app or Windows service) const net = require('net'); const server = net.createServer((socket) => { console.log('Connected to control app'); // Listen for messages from your Electron app socket.on('data', (data) => { const incomingMsg = data.toString().trim(); console.log(`Received command: ${incomingMsg}`); // Example: Send a response back to the control app socket.write(`Acknowledged: ${incomingMsg}\n`); // Add your logic here—like executing system commands, fetching system stats, etc. }); socket.on('end', () => { console.log('Disconnected from control app'); }); }); // Listen on all network interfaces, port 3000 server.listen(3000, '0.0.0.0', () => { console.log('Waiting for control app connections on port 3000'); });
Step 2: Connect from Your Electron App
In your Electron main process, use the net module to connect to each remote PC's IP and send/receive messages:
// Electron main process code const net = require('net'); function connectToDevice(deviceIp) { const client = net.connect({ port: 3000, host: deviceIp }, () => { console.log(`Connected to ${deviceIp}`); // Send an initial message or command client.write('Check system status'); }); // Handle responses from the remote PC client.on('data', (data) => { const response = data.toString(); console.log(`Response from ${deviceIp}: ${response}`); // Update your Electron UI with this data if needed }); // Handle connection errors (e.g., device is offline) client.on('error', (err) => { console.error(`Failed to connect to ${deviceIp}: ${err.message}`); }); return client; } // Example: Loop through your list of device IPs const networkDevices = ['192.168.1.102', '192.168.1.105']; networkDevices.forEach(ip => connectToDevice(ip));
If you need to broadcast a message to all devices at once (like a global notification), use the dgram module for UDP instead—it’s perfect for one-to-many communication without maintaining individual connections.
If you prefer a higher-level approach, setting up a lightweight HTTP API on each remote PC makes it easy to send commands and fetch data using standard HTTP requests.
Step 1: Spin Up an Express Server on Remote PCs
Use Express to create simple endpoints for receiving messages and returning data:
// Remote PC Express service const express = require('express'); const app = express(); app.use(express.json()); // Parse JSON request bodies // Endpoint to receive messages/commands from the control app app.post('/api/receive-command', (req, res) => { const { command } = req.body; console.log(`Executing command: ${command}`); // Add your command handling logic here const responseData = { status: 'success', message: `Command "${command}" received`, systemStats: { cpu: '32%', memory: '58%' } }; res.json(responseData); }); // Endpoint to fetch device status on demand app.get('/api/get-status', (req, res) => { res.json({ uptime: '4h 12m', activeUsers: 1, diskUsage: '72%' }); }); app.listen(3000, '0.0.0.0', () => { console.log('HTTP API running on port 3000'); });
Step 2: Send Requests from Electron
Use Node.js's built-in fetch API (or axios if you prefer) to interact with these endpoints. In Electron, you can run this in the main process, or use a preload script to expose functionality to the renderer process:
// Electron main process code async function sendCommandToDevice(deviceIp, command) { try { const response = await fetch(`http://${deviceIp}:3000/api/receive-command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command }) }); const result = await response.json(); console.log(`Response from ${deviceIp}:`, result); return result; } catch (err) { console.error(`Failed to send command to ${deviceIp}:`, err.message); } } async function getDeviceStatus(deviceIp) { try { const response = await fetch(`http://${deviceIp}:3000/api/get-status`); return await response.json(); } catch (err) { console.error(`Failed to fetch status for ${deviceIp}:`, err.message); } } // Example usage sendCommandToDevice('192.168.1.102', 'clean-temp-files'); const status = await getDeviceStatus('192.168.1.102');
If you need instant, real-time updates (like live system monitoring or chat-style messages), WebSockets are the way to go. They maintain a persistent connection, allowing both sides to send messages at any time.
Step 1: WebSocket Server on Remote PCs
Use the popular ws module to set up a WebSocket server:
// Remote PC WebSocket server const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 3000 }); wss.on('connection', (ws) => { console.log('Control app connected'); // Listen for incoming messages ws.on('message', (data) => { const message = data.toString(); console.log(`Received: ${message}`); // Send a real-time response ws.send(`Received your message at ${new Date().toLocaleTimeString()}`); }); // Send periodic updates (e.g., live CPU stats) setInterval(() => { ws.send(JSON.stringify({ cpuUsage: Math.floor(Math.random() * 100) + '%' })); }, 5000); ws.on('close', () => { console.log('Control app disconnected'); }); }); console.log('WebSocket server running on port 3000');
Step 2: WebSocket Client in Electron
Connect to each remote PC's WebSocket server and handle real-time messages:
// Electron main process code const WebSocket = require('ws'); function connectToWebSocket(deviceIp) { const ws = new WebSocket(`ws://${deviceIp}:3000`); ws.on('open', () => { console.log(`WebSocket connected to ${deviceIp}`); ws.send('Start live monitoring'); }); ws.on('message', (data) => { const message = JSON.parse(data); console.log(`Real-time update from ${deviceIp}:`, message); // Update your Electron UI with live data here }); ws.on('error', (err) => { console.error(`WebSocket error with ${deviceIp}:`, err.message); }); ws.on('close', () => { console.log(`WebSocket disconnected from ${deviceIp}`); // Optional: Add reconnection logic here }); return ws; } // Example usage const wsConnection = connectToWebSocket('192.168.1.102'); // Send a message later // wsConnection.send('Stop live monitoring');
- Service Deployment: Package the remote PC services into standalone executables (use
pkgor Electron builder) so users can run them easily, or set them up as auto-starting system services. - Permissions: Make sure both your Electron app and the remote services run with sufficient permissions (e.g., admin rights if you need to execute system commands).
- Error Handling: Add retry logic for failed connections, handle timeouts, and give clear feedback in your Electron UI if a device is offline.
- Security: Even on a local network, add basic authentication (like API keys or tokens) to prevent unauthorized access to your remote services.
内容的提问来源于stack exchange,提问作者Joseph

