Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Server crashed when Refresh Browser

I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.

Below is the error message:

events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: read ECONNRESET
    at _errnoException (util.js:1022:11)
    at TCP.onread (net.js:615:25)

I used the node --inspect index.js, but could not find the point.

Below is the code of index.js:

const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');

var handleError = function (err,res) {
  res.writeHead(404);
  res.end();
}

var server = http.createServer(function (req, res) {
  console.log("Responding to a request.");
  var filePath = extract(req.url);
  console.log("filePath:"+filePath);
  fs.readFile(filePath,function (err,data) {
    if(err){
      handleError(err,res);
      return;
    }else {
      res.end(data);
    }
  })
})

server.listen(3000);

When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.

Below is code of websockets-server.js:

const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
  port:port
});

var message = [];

console.log('websockets server started');

ws.on('connection', function (socket) {
  console.log('client connection established');

  message.forEach(function (msg) {
    socket.send(msg);
  })

  socket.on('message', function (data) {
    console.log('message received: ' + data);
    message.push(data);
    ws.clients.forEach(function (clientSocket) {
      clientSocket.send(data);
    });
  });
});

Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.

extract.js below:

const path = require('path');

var extractFilePath = function (url) {
  var filePath;
  var fileName = 'index.html';

  if(url.length > 1){
    fileName = url.substring(1);
  }
  console.log('The fileName is: ' + fileName);

  filePath = path.resolve(__dirname, 'app', fileName);
  return filePath;
}
module.exports = extractFilePath;
like image 924
周雪静 Avatar asked May 13 '26 06:05

周雪静


1 Answers

I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:

window.onbeforeunload = function () {
    ws.close();
}

close connection before reload, then the error will not reappear.

like image 198
Lucien Avatar answered May 14 '26 18:05

Lucien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!