1.手機端Auto.js腳本:
每部手機需要在連接時發送一個唯一的標識符(如設備ID),并接收服務器發送的指令以執行指定的腳本。
// Auto.js腳本連接WebSocket服務器并發送設備ID
var WebSocket = require('ws');
var ws = new WebSocket('ws://your_computer_ip:8080');
var deviceID = "phone1"; // 設備唯一標識符// 當與服務器建立連接時,發送設備ID
ws.on('open', function() {console.log('Connected to server');ws.send(JSON.stringify({ type: 'register', id: deviceID }));
});// 處理從服務器接收的消息
ws.on('message', function(data) {var message = JSON.parse(data);if (message.type == 'command') {executeCommand(message.command);}
});// 根據指令執行操作
function executeCommand(command) {if (command.action == 'run_script') {var scriptName = command.scriptName;if (files.exists(scriptName)) {engines.execScriptFile(scriptName);} else {console.log('Script not found: ' + scriptName);}}// 添加更多操作
}// 當與服務器斷開連接時,記錄日志
ws.on('close', function() {console.log('Disconnected from server');
});
2.電腦端Node.js WebSocket服務器:
在服務器中,維護一個客戶端連接列表,并根據設備ID發送指令。
// Node.js WebSocket服務器
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });let clients = {};// 當有新的客戶端連接時
wss.on('connection', function(ws) {ws.on('message', function(message) {let msg = JSON.parse(message);if (msg.type == 'register') {// 記錄客戶端的設備ID和連接對象clients[msg.id] = ws;console.log(`Device ${msg.id} connected`);}});// 當客戶端斷開連接時ws.on('close', function() {for (let id in clients) {if (clients[id] === ws) {delete clients[id];console.log(`Device ${id} disconnected`);break;}}});
});// 發送指令到特定設備
function sendCommand(deviceID, command) {if (clients[deviceID] && clients[deviceID].readyState === WebSocket.OPEN) {clients[deviceID].send(JSON.stringify({ type: 'command', command: command }));} else {console.log(`Device ${deviceID} is not connected`);}
}// 示例:向手機1發送執行腳本的指令
sendCommand('phone1', { action: 'run_script', scriptName: '閑魚.js' });
3.運行服務器和測試:
確保每部手機上的Auto.js腳本正常運行并能連接到服務器。在電腦上運行Node.js服務器。使用sendCommand函數向特定設備發送指令,測試是否手機1能接收到并執行閑魚.js腳本。