Node: Connect angular 6 client to Node server - node.js

I have node TCP socket server that i implemented using net module as shown in below
const net = require("net");
const server = net.createServer();
server.on("connection", function (socket) {
socket.setEncoding('utf8');
socket.on("data", function (d) {
}
}
socket.on("end", function () {
clients.splice(clients.indexOf(socket), 1);
console.log('end event on socket fired');
});
and i want my angular 6 app as a client to this TCP server. So i explore on the internet i only get with socket.io. Basic scenario is i have two clients one is raspberry which communicate on TCP/IP to my server and one is angular app that communicate with server using http. Any idea how to achieve this?

As of my knowledge plain TCP/UDP connections from the browser is currently deprecated because of security issues. I believe you may have to use WebSockets both on angular and node sides.

Related

How to establish SSL/TLS socket connection with NodeJS

I've created a very simple socket server with NodeJS (v8.11.3) and it's working fine. My goal is to keep a socket connection opened with an electronic device (IoT).
QUESTION: How to make communication secure, that is, how to make socket/SSL socket communication? NOTE: I have also created a self-signed certificate for testing.
The test socket server (without security) is the one below. I have no experience with NodeJS, so I think there are a lot better ways to establish a socket connection...
const net = require('net')
net.createServer(socket => {
socket.on('error', (err) => {
console.log('Socket Error: ')
console.log(err.stack)
})
socket.on('data', function(data){
msg = ''
msg = data.toString();
socket.write(msg)
console.log(msg)
})
}).listen(8001)
You can use the built-in tls module, which provides extensions of net.Server and net.Socket. As such, it works about the same as the net server creation, with more options and more events. There is a simple example in the tls.createServer section, which shows a basic server close to your code here.

Socket.io-based app running through node proxy server disconnecting all sockets whenever one disconnects

I made a basic chat app using node.js, express and socket.io. It's not too different from the tutorial chat app for socket.io, it simply emits events between connected clients. When I ran it on port 3001 on my server, it worked fine.
Then I made a proxy server app using node-http-proxy which listens on port 80 and redirects traffic based on the requested url to various independent node apps I have running on different ports. Pretty straightforward. But something is breaking. Whenever anyone disconnects, every single socket dis- and re-connects. This is bad for my chat app, which has connection-based events. The client consoles all show:
WebSocket connection to 'ws://[some socket info]' failed: Connection closed before receiving a handshake response
Here's what I think are the important parts of my code.
proxy-server.js
var http = require('http');
var httpProxy = require('http-proxy');
//create proxy template object with websockets enabled
var proxy = httpProxy.createProxyServer({ws: true});
//check the header on request and return the appropriate port to proxy to
function sites (req) {
//webapps get their own dedicated port
if (req == 'mychatwebsite.com') {return 'http://localhost:3001';}
else if (req == 'someothersite.com') {return 'http://localhost:3002';}
//static sites are handled by a vhost server on port 3000
else {return 'http://localhost:3000';}
}
//create node server on port 80 and proxy to ports accordingly
http.createServer(function (req, res) {
proxy.web(req, res, { target: sites(req.headers.host) });
}).listen(80);
chat-app.js
/*
...other modules
*/
var express = require("express");
var app = exports.app = express(); //I probably don't need "exports.app" anymore
var http = require("http").Server(app);
var io = require("socket.io")(http);
io.on("connection", function (socket) {
/*
...fun socket.on and io.emit stuff
*/
socket.on("disconnect", function () {
//say bye
});
});
http.listen(3001, function () {
console.log("listening on port 3001");
});
Now from what I've read on socket.io's site, I might need to use something to carry the socket traffic through my proxy server. I thought that node-http-proxy did that for me with the {ws: true} option as it states in their docs, but apparently it doesn't work like I thought it would. socket.io mentions three different things:
sticky session based on node's built in cluster module
socket.io-redis, which allows separate socket.io instances to talk to each other
socket.io-emitter, which allows socket.io to talk to non-socket.io processes
I have exactly no idea what any of this means or does. I am accidentally coding way above my skill level here, and I have no idea which of these tools will solve my problem (if any) or even what the cause of my problem really is.
Obligatory apology: I'm new to node.js, so please forgive me.
Also obligatory: I know other apps like nginx can solve a lot of my issues, but my goal is to learn and understand how to use this set of tools before I go picking up new ones. And, the less apps I use, the better.
I think your intuition about needing to "carry the socket traffic through" the proxy server is right on. To establish a websocket, the client makes an HTTP request with a special Upgrade header, signalling the server to switch protocols (RFC 6455). In node, http.Server instances emit an upgrade event when this happens and if the event is not handled, the connection is immediately closed.
You need to listen for the upgrade event on your http server and handle it:
var proxy = httpProxy.createProxyServer({ws: true})
var http = http.createServer(/* snip */).listen(80)
// handle upgrade events by proxying websockets
// something like this
http.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head, {target:sites(req.headers.host)})
})
See the node docs on the upgrade event and the node-http-proxy docs for more.

Create web socket streams between a server and arbitrary NodeJS processes

Having a server running on localhost:5000, I want to connect to that server from another NodeJS process, via web sockets.
From my experience with web sockets, I always needed the server object to create a web socket server.
var http = require('http');
// create http server
var server = http.createServer(function(req, res) {
// serve files and responses
...
});
// Socket.io server listens to our app
var io = require('socket.io').listen(server);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', console.log);
});
server.listen(3000);
This is a tiny example using socket.io. Without having access to get the server variable (since this server will be deployed some where in the cloud), how can I connect via web sockets to this server?
An ugly solution would be via HTTP requests, but that's not web sockets. I want to keep the connection open and pipe data there.
How can I do that?
You get the socket.io-client module, require() it into your other nodejs server and use that client module from your other server (which will be the client in this case) and connect from that server to this one.
Example code here: https://github.com/automattic/socket.io-client
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});

Adobe AIR- connection issues with socket.io

I have a desktop app in Adobe Air (flex).
I have used flashSocket.io library in my app to communicate with socket.io on node.js server.
It works perfectly for most of the clients.
But for some random client the flex app is not able to create a connection with the socket.io server. It constantly throws connection error and close error on flex. The clients are not behind any firewalls or proxy server.
The console has warning like
Web Socket Connection Invalid
I guess this for those clients who are not able to connect.
Since its working for majority of the users i don't know where should i look into. Also, i am unable to reproduce this on my side.
Here's the Server Code:
var io = require('socket.io').listen(app);
app.listen(8080, function() {
console.log('%s listening at %s', app.name, app.url);
});
io.configure(function() {
io.set('transports', ['flashsocket']);
io.set('flash policy port', 843);
});
Flex code:
socket = new FlashSocket("http://domain.com:8080/");
socket.addEventListener(FlashSocketEvent.CONNECT, onConnect);
socket.addEventListener(FlashSocketEvent.MESSAGE, onMessage);
socket.addEventListener(FlashSocketEvent.CLOSE, onDisconnect); //only close and connect_error event is always fired for certain clients
socket.addEventListener(FlashSocketEvent.CONNECT_ERROR, onConnectError);
Any help would be highly appreciated.
Use a different port, we're using 443.

NodeJS connect to wss on another server

There is a wss on another server that I'd like to connect to. Let's say its address is: wss://123.123.123.12:8843
I have a nodejs/expressjs app. How do I connect to it using socket.io? I know how to implement socket.io for a server/client setup, but how do I do it for two servers (one of which I don't have access to).
How do I setup my expressjs app to connect to the wss? Is there a way using socket.io or do I need to do it another way?
Socket.IO isn't a WebSocket. It is a transport system that supports WebSockets, but if you want to interface with other WebSockets, you'd have better luck using the ws module, which Socket.IO uses internally. This is how it's used:
var WebSocket = require('ws');
var ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function() {
ws.send('something');
});
ws.on('message', function(data, flags) {
// flags.binary will be set if a binary data is received
// flags.masked will be set if the data was masked
});
If you actually just want to communicate with another Socket.IO server, then install the client on the server. It's used the same way as you would use with a browser client.
npm install socket.io-client
And then usage:
var socket = require('socket.io')('http://host/path');
socket.on('connect', function() {
socket.on('event', function(data) { });
socket.on('disconnect', function() { });
});

Resources