1 回答

TA貢獻1840條經(jīng)驗 獲得超5個贊
我們可以假設(shè) socket-io 不適合您,因為您擁有的服務(wù)器聽起來像是典型的 tcp-socket 服務(wù)器,而不是 socket.io 服務(wù)器(需要特殊的標頭)或 web-套接字服務(wù)器。
所以你只需要“網(wǎng)絡(luò)”庫來完成這項工作。
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')
該腳本將:
啟動套接字客戶端
連接成功,客戶端發(fā)送消息
客戶端收到來自該消息的回復(fù)
客戶端打印對終端的響應(yīng)
請注意,TheSkyX 對每條消息有 4096 字節(jié)的限制,超過這個限制,我們將需要對消息進行分塊。所以你可能希望保持 js 代碼簡短和精確。
我給出的那個片段是最小的,它不處理來自服務(wù)器的錯誤。如果你愿意,你可以添加
client.on("error", .. )
來處理它。您直接從瀏覽器連接到套接字服務(wù)器的觀點非常有趣,不幸的是,出于安全考慮,現(xiàn)代瀏覽器本身不允許這樣做
添加回答
舉報