簡體   English   中英

websocket 連接在寫入文件時關閉

[英]websocket connection closes upon writing to file

所以我使用 websockets (ws) 將客戶端連接到服務器。 我成功地將消息發送到服務器並將其發送回客戶端。問題是當我嘗試將接收到的消息寫入文件時,服務器斷開了客戶端的連接。 消息已成功寫入,但我最終斷開了客戶端連接。 看起來關於寫入功能的東西斷開了我的客戶端。 我正在使用 fs.writFile(),我已經嘗試過 fs.createWriteStream()。 但是,讀取文件不會斷開連接。

const http = require('http');
const WebSocket = require('ws')
const fs = require('fs');

let counts = [0,0]
const server = http.createServer((req,res)=>{
    console.log(' Received request for ' + request.url);
});

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection',(ws)=>{
    console.log("serving...")

    ws.on('message',(message)=>{
        console.log("Received:"+message)

        if(message ==='1'){
            counts[0]=parseInt(counts[0])+1
            fs.writeFile('votecnts.txt',`${counts[0].toString()} ${counts[1].toString()}`,(err) =>{
                if(err) throw err
            })
        }
        else if (message==='2'){
            counts[1]=parseInt(counts[1])+1
            fs.writeFile('votecnts.txt',`${counts[0].toString()} ${counts[1].toString()}`,(err) =>{
                if(err) throw err
            })
        }
        else{console.log(typeof(message))}

        ws.send("cand_one: "+counts[0].toString()+"\n cand_two: "+counts[1].toString())    
    })



    ws.on('close',function(){
        console.log("lost client")
    })
})

所以我想通了。 我在開發時在本地主機上同時運行服務器和客戶端。 因此文件目錄是相同的。 后來我發現由於安全原因,不可能在客戶端用 javascript 寫入文件。 所以我所做的就是將服務器的 url 更改為遠程機器,並且我能夠使用服務器代碼寫入文件。 特別是上面代碼中的 writeFile() 函數。 我實際上不必接觸我的代碼。 這只是關於配置和設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM