node.js - How to handle this error when use nodejs writing a chat server? -
here code:
var net = require('net'); var clientlist = []; var chatserver = net.createserver(function(socket){ socket.write("hi\n"); clientlist.push(socket); socket.setencoding('utf-8'); socket.on('data', function(data){ (var = 0; < clientlist.length; i++) { clientlist[i].write(data); }; socket.end(); }); }).listen(4000);
when access http://127.0.0.1:4000
, give me response:
hi / http/1.1 host: localhost:4000 connection: keep-alive cache-control: max-age=0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 user-agent: mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, gecko) chrome/42.0.2311.135 safari/537.36 accept-encoding: gzip, deflate, sdch accept-language: en-us,en;q=0.8,zh-cn;q=0.6,zh;q=0.4
but program crashed: here output form console:
c:\users\elqstux\desktop>node wy.js events.js:85 throw er; // unhandled 'error' event ^ error: socket has been ended other party @ socket.writeafterfin [as write] (net.js:289:12) @ socket.<anonymous> (c:\users\elqstux\desktop\wy.js:13:18) @ socket.emit (events.js:107:17) @ readableaddchunk (_stream_readable.js:163:16) @ socket.readable.push (_stream_readable.js:126:10) @ tcp.onread (net.js:529:20)
i can't fine reason why there error.
when new client connects, storing incoming socket in clientlist
array, data arrives on socket, closing socket.end()
, not removing array. so, when iterate through array sending data sockets in clientlist
array, have sockets in list no longer open generates error.
the socket.writeafterfin
error means you're trying write socket after you've closed it.
that explains error. don't know you're trying accomplish i'm not sure code suggest avoid error.
also, can handle errors on socket (so server won't stop) adding:
socket.on('error', function(err) { // process error here });
and, need handle close event if client closes socket:
socket.on('close', function() { // clean references socket no longer open // remove `clientlist` array , other references have });
Comments
Post a Comment