http.createServer() vs http.request() - javascript

I think I understand this below code:
var assert =require("assert");
var http = require("http");
var server = http.createServer(function(req, res){
res.writeHead(200, {"Content-Type" : "text/HTML"});
res.write("hello, world.\r\n");
res.end();
});
server.listen(8000, function(){
console.log("Listening on port 8000");
});
We create a server and set it up to listen on port 8000 and when i go to page localhost:8000 in the browser I think it initiates a request to the server for something(can someone help me specify what that is) then the server responds with a header and "hello world"
the next part I'm not so sure of:
var req = http.request({
port : 8000
}, function(res){
console.log("HTTP header:", res.headers);
res.on("data", function(data){
console.log("Body:", data.toString());
assert.equal("hello, world.\r\n", data.toString());
assert.equal(200, res.statusCode);
// server.unref(); //client disconnected...sever stop listening
})
})
req.end()
^^^ Is this server sending a request to the browser
I know the doc says
Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.
does that mean that server is sending a request. you could randomly send a request to a client? and if so how does it get the data? Doesn't there have to be some type of initiation from the browser/ client to send over the data how does res.on("data" ) get the data?

Related

Node.js HTTP Server- Taking long time to load and is not sending data

I am learning node.js, While using HTTP module i tried to create by own server as per instruction of video tutor but my server is not sending any response at port 3000 and port 8000.
*
const http = require('http');
const server = http.createServer((req, res) => {
if(req === '/'){
res.write('Hello world, first program in server using http module');
res.end();
}
if(req === '/api/courses'){
res.write(json.strigify([1,2,3]));
res.end();
}
});
server.listen(8000);
console.log('Listening #port 8000');
*
The strict comparison req === '/' is comparing a request object with a string, a comparison which will never be true.
You likely meant to use: req.url === '/'

Client program for continuous talking to an echo server in nodejs

I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request
What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.

Loading html page on nodeJS won't load until keyboard interrupt

I am new to nodeJS. I am trying to load an index.html page onto my 8080 port and have this:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
I have 3 files in the same directory: index.html, style.css, server.js. I start up the server and the page will not load until after I hit cntrl + c. Why is this?
You have written the data to the response, but you have not finished the response. Put res.end(); after your res.write function.
Without this, the browser keeps waiting for more data from the server. When you shut down the server with Ctrl-C, the server closes the connection, and the browser renders what it received.
If you are new to Node, I would recommend looking into something like Express, which handles a lot of important things like routing (what URLs go to which pages) for you and will save you a lot more if statements in the future.

Send data from websocket to socket.io

I used websocket interface to connect to websocket server . what if i want send data that i receive from the websocket server through my websocket interface to client connected to me through http server , should i use socket.io ?
so at the end i will have socket.io attached to to http server and websocket interface to get data and in case of message come will be send to client through socket.io . is that the best setup ?
Code Example :
// Require HTTP module (to start server) and Socket.IO
var http = require('http'),
io = require('socket.io');
var WebSocket = require('ws');
var ws = new WebSocket('ws://localhost:5000');
// Start the server at port 8080
var server = http.createServer(function (req, res) {
// Send HTML headers and message
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function (data, flags) {
// here the data will be send to socket.io
});
// Add a connect listener
socket.on('connection', function (client) {
// Success! Now listen to messages to be received
client.on('message', function (event) {
console.log('Received message from client!', event);
});
client.on('disconnect', function () {
clearInterval(interval);
console.log('Server has disconnected');
});
});
Yes, your design is correct.
However, one thing that you should keep in mind is take care of sending the message to the correct client after authentication. In my opinion, it is very easy to make this mistake, partially because of the simplicity of messaging using websockets.

Node.js + socket.io: app on server not working correctly

I'm new to node.js and socket.io and tried to connect the server to the client with the example from http://socket.io/#how-to-use. (no localhost)
Server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html'+err);
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.broadcast.send(msg);
});
socket.on('disconnect', function () { });
});
Client:
<html><head><script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connect', function () {
alert('connected.');
socket.on('message', function (msg) {
// my msg
alert('message received: '+msg);
});
socket.send('hi');
});
</script>
</head><body>This is the content :)</body>
</html>
Google Chrome displays in the console:
Unexpected response code: 502
Also, after receiving every message, Chrome adds
GET http://[myServer]/socket.io/1/?t=1352313105809 socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
maybeReconnect
to the console.
Wheres the problem?
The examples from the How-To page all use port 80, which is common for serving websites.
However, you use port 8080 in your example.
Check your web browser's console if it even loads the socket.io script.
You may need to provide http://localhost:8080/socket.io/socket.io.js as explicit url and connect with io.connect('http://localhost:8080');
If the above does not work, please share some insight on what port your web server runs on.
There is no code to actually handle any incoming messages server-side in your (updated) example.
`socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.send(msg);
});
should at the very least send the message back to the client - your alert is only triggered when the client receives a message. Does the node.js console output any incoming or sent messages? A few lines of my node.js console look like the following upon connecting.
debug - client authorized
info - handshake authorized ...
debug - setting request GET /socket.io/1/...
debug - set heartbeat interval for client ...
debug - client authorized for
debug - websocket writing 1::
debug - sending data ack packet

Categories

Resources