node.js - broadcast message to all the connected - javascript

So we have the following node.js code -
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
response.end(");
}).listen(8125);
Let's say I want to broadcast a message to all the connected users,
write method of response in the createServer function doesn't do that.
So how can I broadcast message to all the connected users/clients?
There is a way doing it with pure Node.js? because I'm just learning it now, and I prefer using pure node.js for now..

These are HTTP requests, therefore it isn't possible. HTTP requests start on first connection and end when all the data has been sent.
In your case, the data is
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
And then connection is ended
response.end(");
If you're looking for something to keep live connections with, take a look at these:
socket.io - a realtime transport library that supports all platforms, and falls back for older software.
WebSocket-Node - a client and server websocket implementation.
Faye - publish-subscribe messaging system that uses the Bayeux protocol.
I have only used socket.io and this is how broadcasting is done.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
});

Related

Rest API based TCP client using Node js

I have tried to create TCP Client with rest api using nodejs and also used net module to establish tcp connection to send/receive data. The main idea is to use this restAPI from browser to load test TCP Connections.
Here in my case there are 2 steps involved while load testing TCP.
1) send initial TCP request which has token for authentication.
2) then send other TCP request to send some data.
The issue is when i try to send 2nd TCP request after authentication. Getting response as invalid session.
Please suggest if i can send TCP request for authentication and using same session/connection while making subsequent requests.
I am new to node js. My Apologize if I have not provided enough details or done some thing invalid.
Initially I have used Packet Sender application and enabled persistent TCP Connection option in it. It worked well as expected but this is for single user and cant use this tool for load testing. Here in this tool with persistent TCP enabled I can see the local port is fixed and not changing upon sending multiple requests but with my node js code i can see the local port is getting changed upon every new request.
I have also used TCP Sampler in Jmeter with reuse Connection option but not working when i send 2nd request after authentication.
var Net = require('net');
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/api/push', function (req, res) {
var reqBody = req.body.reqBody;
var req = JSON.stringify(reqBody);
const client = new Net.Socket({
allowHalfOpen: true
});
client.connect({
port: req.body.port,
host: req.body.host
}, function () {
client.write(req);
});
client.on('data', function (chunk) {
res.write(chunk.toString());
//Tried to use client connection information, but didnt worked not sure if i missed something.
console.log(JSON.stringify(client));
// Tried commenting below client.end but no luck.
client.end();
});
client.on('end', function () {
res.end();
});
client.on('error', function (err) {
console.log("Error: " + err.message);
res.write(err.message);
client.end();
});
});
app.listen(1234, () => {
console.log("Server running on port 1234");
});
1) send restAPI with TCP server host/port and request body for authentication.
2) send another restAPI to use same TCP connection and send data. but it failed for mere
Inspect the behavior and get the cookies details and preserve the same in HTTP cookie manager to reuse the same session for the second request. Just adding http cookie manager also might work. Please check,

Electron NodeJS server to server communication using POST

I am working on an assignment for school, and I have decided to make a chat application using Electron and NodeJS. All of the GUI is programmed, except for the server-side of things. My plan was to have two servers, where each would act as its own client AND server, only communicating with each other to send messages.
How would I get each server to communicate using POST requests? Does anybody know any fully functioning npm modules that can be used for this?
you need to use in server A : socket.io
in server B: socket.io-client
Like this:
server A
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
server B
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
This can be done with React js, there's quite examples on github.
Take a look at this examples:
https://github.com/ncuillery/react-chat-project
https://github.com/keithyong/chat-room
It's nice to see someone using Electron, I've just finished my first project with it, and I'm amazed.
As #Arcath has stated, you must use socket.io, it talks between frontend and backend. Whenever someone sends a chat message, React.js handles that message, and emits a socket message which the server recieves. The server then adds the socket message into the database.

How to create a node.js server?

I'm trying to create my first node.js server and I have some problems.
When I use
var http = require("http");
var server = http.createServer();
server.listen(8888);
No connection can be established to the server.
But when I use this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
The server lands ok.
I used this in a file called server.js and runned the command node server.js. I'm using v 0.12.0
What am I missing? Why the server doesn't work on the first case?
The first block of code creates a server and listens on a port.
When you point a browser at it, the browser makes a request and then waits for a response.
You haven't told the server what to respond with, so it sits there doing nothing.
Eventually the browser times out.
In the second set of code, you've told the server how to respond to requests.

HTML code from node js not interpreted as such by the browser

I have created my first node js application: a simple webserver.
Here's the code:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("ARD Tagesschau\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
When I connect to the server via my browser I get the full string specified in my code as a web page.
Shouldn't the browser interpret that HTML code and display a link? Why do I get the full HTML code shown as plain text?
You have explicitly said that you are returning plain text, not HTML. The browser therefore treats it as plain text.
If you want HTML to be treated as HTML then say it is HTML:
{"Content-Type": "text/html"}
(Although you should send back an HTML document and not a fragment of HTML).
Following Code works for me:
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end("ARD Tagesschau\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
You need to set the Headers. For more information check in Node API docs here.
Check the difference in your firebug or dev tools to understand how browser interprets differently based on Header Content-Type.

Node.js and web-socket-js simple client server not opening

My server.js seems to be correct..
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "mysite.com");
console.log('Server running at mysite.com:1337/');
The meat of my client is below.
function init() {
// Connect to Web Socket.
// Change host/port here to your own Web Socket server.
ws = new WebSocket("ws://mysite.com:1337");
// Set event handlers.
ws.onopen = function() {
output("onopen");
};
}
If I go to http://www.mysite.com:1337 I correctly receive Hello World! However, when I try to connect using my client, and debug in Fire bug, I get the following output.
[WebSocket] connected
[WebSocket] request header: GET / HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: mysite.com:1337 Origin: http://www.mysite.com Cookie: Sec-WebSocket-Key1: 115 17 p^!x-93 IERc16 7 Sec-WebSocket-Key2: 1 75 7Z i `. 8u $l031 4j9
[WebSocket] sent key3: ±Ôñ<g
[WebSocket] closed
And the WebSocket is automatically closed before I have any chance to do anything. Can anyone please shed some light on the error I am receiving and what do you think I should do?
You have created a node.js HTTP server but you are trying to connect to it as a WebSockets server. The WebSockets protocol is not plain sockets and it is not plain HTTP request. WebSockets have an HTTP like handshake but after that you have a full-duplex connection (like sockets and unlike HTTP) that has a small amount of message framing (unlike plain sockets).
Try using Socket.IO or node-websocket-server if you want to create a node.js WebSockets server. On the other hand if you are wanting to connect from Javascript to a regular HTTP server then use one of the great Javascript libraries with AJAX support such as jQuery.

Categories

Resources