Hy, im making a simple http server with sockets from node.js native net module that run on "localhost:4000" and gives only "hello, world!" webpage.
The server is running OK and on my server i make some debugs with console.log() menssages: "listening connections", "client connected", "received data" and "sending data".
My problem is when i go on browser and open the webpage im getting 3 connections: 1- "GET / HTTP/1.1" 2- "GET /favicon.ico HTTP/1.1" and the third connection dont request anything only connects to server.
Here is my webserver code:
const net = require('net') //import net module
const ip = "localhost"; //ip of connection
const port = 4000; //port of connection
const response = "HTTP/1.1 200 OK\n"+
"Content-Type: text/html; charset=UTF-8\n"+
"Content-Encoding: UTF-8\n"+
"Accept-Ranges: bytes\n"+
"Connection: keep-alive\n\n"+
"<h1>Hello, world!</h1>"; //"webpage" http response
const server = net.createServer(); //create server
server.listen(port, ip); //starts server
server.on("listening", () => {
console.log("-Listening connections");
}); //event called on servers starts listening for connections
server.on("connection", handleConnection); //event called when the client has connected
function handleConnection(socket){ //this callback runs when client connects
console.log("("+socket.remoteAddress+":"+socket.remotePort+") connected");
socket.on("data", (data) => { //event called when client send data to server
console.log("-received data from: "+socket.remoteAddress+":"+socket.remotePort);
console.log(data.toString());
socket.write(response, () => { //sends the response (webpage) to client
console.log("-sending response: "+socket.remoteAddress+":"+socket.remotePort)
socket.end(); //close client connection
});
});
socket.on("close", () => { //event called when client connection has closed
console.log("-socket close");
});
}
And this is the console.log messages when browser connects:
-Listening connections
(127.0.0.1:57306) connected
-received data from: 127.0.0.1:57306
-sending response: 127.0.0.1:57306
-socket close
(127.0.0.1:57308) connected
-received data from: 127.0.0.1:57308
-sending response: 127.0.0.1:57308
-socket close
(127.0.0.1:57309) connected
server remains listening (because it only close after receiving a request) but without more requests and if i refresh the page, the connection seems to be continuing where it left off, reusing the last socket conection alive before. Back to console.log message above were has finishied on "(127.0.0.1:57309) connected", after refresh, the browser connects to the socket that was aliving and the log messages are:
...
...(same msg above)
...
-received data from: 127.0.0.1:57608
-sending response: 127.0.0.1:57608
-socket close
...
...(and keeping this loop every page refresh, like reusing las socket openned)
...
Lastly... how to handle this browser requests? I just want to response the "webpage get request" and nothing more. Why browser resquest 3 requisitions?