WebSocket Control WebSocket Control Panel
确保服务器能够处理来自网页端的命令,并将命令转发到相应的移动设备。
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`); } else if (msg.type === 'sendCommand') { // 转发命令到指定设备 let targetDeviceID = msg.deviceID; let command = msg.command; sendCommand(targetDeviceID, command); } }); // 当客户端断开连接时 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`); } }
确保移动端能够连接到服务端,并接收并执行命令。
Auto.js脚本:
// 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'); });