简体   繁体   English

websocket 连接在写入文件时关闭

[英]websocket connection closes upon writing to file

so i am connecting a client to a server using websockets (ws).所以我使用 websockets (ws) 将客户端连接到服务器。 i successfully send msgs to the server and send it back to the client.Problem is when I try to write the received message to a file the server disconnects the client.我成功地将消息发送到服务器并将其发送回客户端。问题是当我尝试将接收到的消息写入文件时,服务器断开了客户端的连接。 The message is successfully written but i end up disconnecting client.消息已成功写入,但我最终断开了客户端连接。 Looks like something about the write functions disconnect my client.看起来关于写入功能的东西断开了我的客户端。 I am using fs.writFile(), I already tried fs.createWriteStream().我正在使用 fs.writFile(),我已经尝试过 fs.createWriteStream()。 Reading the file however does not disconnect it.但是,读取文件不会断开连接。

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")
    })
})

So I figured it out.所以我想通了。 I was running both server and client on localhost while developing.我在开发时在本地主机上同时运行服务器和客户端。 And therefore the file directories are the same.因此文件目录是相同的。 I later found out that it is impossible to write to file in javascript at the client side because of security reasons.后来我发现由于安全原因,不可能在客户端用 javascript 写入文件。 So all I did was to change the url of the server to a remote machine and I was able to write to file using server code.所以我所做的就是将服务器的 url 更改为远程机器,并且我能够使用服务器代码写入文件。 specifically with the writeFile() function in the code above.特别是上面代码中的 writeFile() 函数。 I actually did not have to touch my code.我实际上不必接触我的代码。 It was just about configuration and set up.这只是关于配置和设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM