Electron NodeJS server to server communication using POST - javascript

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.

Related

web sockets - can I send extra info about client in the moment of connecting to server using socket.connect() method

I am working on webrtc project and I have client(s) with input video stream, client that will show input stream and server. I am using webrtc and websockets. Every client is connected to signaling server. I want to know how server can know if connected client is client with input video stream or it is client that will show some streams. Can I send some extra info in the moment of connecting client side to server? Client is written in Javascript and server in Python. Maybe I can use some parameters in socket.connect() method?
Server handling connecting:
#sio.event
async def connect(sid, environ):
print('Connected', sid)
sessionIDs.append(sid)
await sio.emit('ready', room=ROOM, skip_sid=sid)
sio.enter_room(sid, ROOM)
Connecting client to server:
socket.connect();
Just add your data as GET parameter in the websocket url, or use a differente path.
const socket = io("ws://localhost:3000?arg1=1&arg2=2");
// or
const socket = io("ws://localhost:3000/path1");
And on the server to get them:
io.on("connection", (socket) => {
console.log(socket.handshake.query); // prints { x: "42", EIO: "4", transport: "polling" }
});

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,

Sending video and audio stream to server

I am trying to develop a system where there are two clients that can video chat to each other from their browsers over a server. First client sends its video stream to the server and the server sends it to the second client. Also, server saves client's stream as a video file.
I used this WebRTC example: https://github.com/webrtc/samples/blob/master/src/content/getusermedia/source/js/main.js
Server side;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('C:/source/'));
app.get('/', function(req, res) {
res.sendFile('C:/source/index.html');
});
io.on('connection', function(socket) {
console.log('user connected.');
socket.on('disconnect', function() {
console.log('user disconnected.');
});
socket.on('chat message', function(msg) {
?
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Client side;
var socket = io();
while(streaming) {
socket.emit(?);
}
I can't understand that from which source I should emit the video + audio stream of the client to the server. If I successfully upload the stream, I will be able to handle it on server side.
You will need a server that is capable of processing WebRTC media.
I suggest looking into Kurento, Janus, Jitsi Videobridge, FreeSWITCH and Asterisk as alternatives.
This will require a lot more effort from your end, as all will necessitate learning more about them, WebRTC and real-time media processing.
If you need this working yesterday and want to put your efforts and focus elsewhere, you should check out some of the vendors listed in this report about WebRTC PaaS.

Express4 + Socket.io 0.9: different clients get the same non broadcast message

This is a web site using authentication via passport.js.
Two different users connect from different browsers and they request info about their username. The server gets the information and send them back using socket.io.
Everything works like a charm but if the two clients load the page at the same time, the information of one of them goes to both browsers, looks like the server is writing on the same socket.
Server Side:
server.js:
var express = require('express');
var app = express();
var http = require('http').createServer(app).listen(8000),
io = require('socket.io').listen(http);
socket.js:
module.exports = function(app, io) {
...
io.sockets.on('connection', function(socket) {
...
//Build the information about the user and send it back
var userData = userInfo();
socket.emit('userInfo', userData);
...
}
}
Client side (javascript file included in index.ejs):
var socket = io.connect('http://URL:8000');
...
socket.emit("all", {data}); //Hi, I need information about me.
...
socket.on('userInfo', function (data) {
// do some stuff...
});
Server debug in console gets info about the two sockets:
debug - client authorized
info - handshake authorized Cq71N34XLyAJBTIbHCZQ
debug - setting request GET /socket.io/1/websocket/Cq71N34XLyAJBTIbHCZQ
debug - set heartbeat interval for client Cq71N34XLyAJBTIbHCZQ
debug - client authorized for
debug - websocket writing 1::
...
debug - client authorized
info - handshake authorized UF6lOwOFzgjrWY54HCZP
debug - setting request GET /socket.io/1/websocket/UF6lOwOFzgjrWY54HCZP
debug - set heartbeat interval for client UF6lOwOFzgjrWY54HCZP
debug - client authorized for
debug - websocket writing 1::
I´ve been rewriting different parts of the app but I can´t get why the server answers same info to different sockets.

node.js - broadcast message to all the connected

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');
});

Categories

Resources