简体   繁体   中英

Node.js example not working

I followed the two examples on: http://nodejs.org/

The first one worked. Then I tried the second one, which displayed the below error in terminal and ended the process when I entered in the url (localhost:8000). It compiled fine.

$ node node.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ECONNRESET
    at errnoException (net.js:901:11)
    at TCP.onread (net.js:556:19)

Some search results said that it may have been that the port is already in use, but I changed the port in the second example, but still no use.

When I visited localhost:8000 (same port in the code), the webpage displays this:

Echo server
GET / HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

I copied the code from the node.js website exactly, and also tried changing the port numbers. Not sure what is wrong.

Edit : responding to comments

  • No firewall.

  • OS: Linux Mint 15

  • Node v0.10.25

Processes:

$ ps
  PID TTY          TIME CMD
29150 pts/1    00:00:00 bash
29226 pts/1    00:00:00 ps

As pointed out in Hector's comment: the second example is a TCP Server. It is starting up properly (no port already used issues). When you make an HTTP request against this the following will happen

  • Your browser sends HTTP protocol data to the TCP socket
  • node.js writes "Echo Server" back
  • node.js writes HTTP protocol chatter it received from the browser back (that's why you're seeing the "funny" stuff on the "webpage")
  • Your browser closes the socket (probably it is waiting for a timeout, so this might take quite a while)
  • At this point node.js has a pipe open to a writable socket stream and will thus send an error event to the readable socket stream (both of them are var socket here)
  • This error is not handled, hence you see the exception

To "fix" this, either don't use a browser, ie, don't close the socket from the client side (for example you can talk to your script with telnet) or add to your program a handling of the error event like this

socket.on('error', function() {
    console.log("Error is properly handled");
});

(preferably before the call to socket.write ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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