【发布时间】:2020-05-20 04:58:16
【问题描述】:
我已经使用 socket.io 在客户端和服务器之间创建了通信,现在我正在使用 WebSockets 从客户端向服务器发送命令,我想在服务器上运行这些从客户端接收到的命令
这是我的解决方案
HTML(客户端)
<html>
<body>
I am client
</body>
<script>
const ws = new WebSocket('ws://localhost:9898/');
ws.onopen = function() {
console.log('WebSocket Client Connected');
ws.send('npm run build');
};
ws.onmessage = function(e) {
console.log("Received: '" + e.data + "'");
};
</script>
</html>
这里是 server.js
const http = require('http');
const WebSocketServer = require('websocket').server;
const server = http.createServer();
server.listen(9898);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log(message.utf8Data);
connection.sendUTF('Hi this is WebSocket server!');
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
现在,当我们运行服务器并打开 index.html 时,服务器会收到以下消息
`npm run build`
现在如何使用子进程在服务器上运行此命令?
【问题讨论】:
标签: javascript html node.js express websocket