1 回答

TA贡献1840条经验 获得超5个赞
我们可以假设 socket-io 不适合您,因为您拥有的服务器听起来像是典型的 tcp-socket 服务器,而不是 socket.io 服务器(需要特殊的标头)或 web-套接字服务器。
所以你只需要“网络”库来完成这项工作。
const net = require('net');
// module to send a message to TCP-socket server and wait for the response from socket-server
const sendAndReceive = async (client, message) => {
client.write(message);
let response = null
await ( new Promise( (resolve, reject) => {
client.on('data', function(data) {
response = data;
resolve()
});
}))
return response;
}
// send a single message to the socket-server and print the response
const sendJSCode = (message) => {
// create socket-client
const client = new net.Socket();
client.connect(3040, 'localhost', async function() {
console.log('Connected');
// send message and receive response
const response = await sendAndReceive(client, message)
// parse and print repsonse string
const stringifiedResponse = Buffer.from(response).toString()
console.log('from server: ', stringifiedResponse)
// clean up connection
client.destroy()
});
}
sendJSCode('var Out; \n Out="TheSky Build=" + Application.build \n\r')
该脚本将:
启动套接字客户端
连接成功,客户端发送消息
客户端收到来自该消息的回复
客户端打印对终端的响应
请注意,TheSkyX 对每条消息有 4096 字节的限制,超过这个限制,我们将需要对消息进行分块。所以你可能希望保持 js 代码简短和精确。
我给出的那个片段是最小的,它不处理来自服务器的错误。如果你愿意,你可以添加
client.on("error", .. )
来处理它。您直接从浏览器连接到套接字服务器的观点非常有趣,不幸的是,出于安全考虑,现代浏览器本身不允许这样做
添加回答
举报