How to make pure Node.js websocket client? - javascript

Assuming that web sockets based on TCP I have created a simple TCP client, but I cannot get any response from echo.websocket.org. What am I doing wrong?
const connectionData: any = {
protocol: 'ws:',
host: 'echo.websocket.org',
port: '80'
}
var client = new net.Socket();
client.connect(connectionData, function () {
console.log('Connected');
client.write('Reply this.');
});
client.on('data', function (data) {
console.log('Received: ' + data);
});
client.on('close', function () {
console.log('Connection closed');
});

Related

MQTT | Publisher automatically disconnect and connect on his own

I use mosca (for node js) to create a MQTT server and MQTT (still node js) package to create publishers and subscribers. Everything work good except one thing: publisher reload automatically
I guess it may be due to incorrect mqtt.connect options. I read npm mqtt manual but still don't understand my mistake (or mistakes)
P.s. Sorry for my grammatical, I'm not an English speaker
UPD: i'm beginner :)
MQTT Server:
const mosca = require("mosca");
const MqttServer = new mosca.Server({
port: 1884
});
MqttServer.on("clientConnected", function(client) {
console.log('\x1b[0m', 'Клиент ' + '\x1b[32m' + client.id + '\x1b[32m' + ' подключен!' + '\x1b[0m');
});
MqttServer.on("clientDisconnected", function(client) {
console.log('\x1b[0m', 'Клиент ' + '\x1b[32m' + client.id + '\x1b[31m' + ' Отключен' + '\x1b[0m');
})
MqttServer.on("ready", function() {
console.log("Server MQTT Room1 running");
});
MqttServer.on("error", function(error) {
console.log("error!");
client.end();
})
Subscribe script:
const mqtt = require("mqtt");
const options = {
clientId: 'mqtt_room1_SUB',
clean: true
};
const client = mqtt.connect("mqtt://127.0.0.1:1884", options);
client.on("connect", function() {
console.log("Connected");
// connected = client.connected
client.subscribe("room1/temp", { qos: 0 });
});
client.on("message", function(top, message) {
console.log("Current temperature:", message.toString());
});
client.on("disconnect", function () {
console.log('Server disabled.')
})
Publish script:
const mqtt = require("mqtt");
const options = {
clientId: 'mqtt_room1_PUB',
clean: true
};
const client = mqtt.connect("mqtt://127.0.0.1:1884", options);
client.on("connect", function() {
console.log("Connected");
setInterval(() => {
var value = Math.floor(Math.random() * 20);
client.publish("room1/temp", value.toString());
}, 2000);
});
client.on("disconnect", function () {
console.log('Server disabled.');
});

How to maintained network connection in Node.js for unlimited requests

I want to make connection for unlimited times in Nodejs. For example, i write something on some server and after writing on server, server send me response of error (as expected from server) and disconnect. But i want to again make a connection to that server and again want to send request with different parameters. I am not sure where and what logic/code to be put in my following segment of code , so that i can make unlimited requests.
var net = require('net');
var HOST = '40.14.121.178'
var PORT = 12537;
var byteToSend = [0x56, 0x34, ...]
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write(byteToSend);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
EDITED:
actually, i want to make another connection upon disconnect like following style (which is i think wrong)
client.on('close', function() {
console.log('Connection closed');
client.connect(PORT, HOST, function() {
console.log('again CONNECTED TO: ' + HOST + ':' + PORT);
client.write(byteToSend);
});
});
above re connection raise following error.
events.js:174
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at afterWriteDispatched (internal/stream_base_commons.js:78:25)
at writeGeneric (internal/stream_base_commons.js:73:3)
at Socket._writeGeneric (net.js:713:5)
at Socket._write (net.js:725:8)
at doWrite (_stream_writable.js:415:12)
at writeOrBuffer (_stream_writable.js:399:5)
at Socket.Writable.write (_stream_writable.js:299:11)
at bitflipping (C:\Users\...\Desktop\myScripts.js:130:8)
at Socket.<anonymous> (C:\Users\...\Desktop\myScripts.js:104:9)
at Object.onceWrapper (events.js:286:20)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:107:12)
at onwriteError (_stream_writable.js:430:5)
at onwrite (_stream_writable.js:461:5)
at _destroy (internal/streams/destroy.js:49:7)
at Socket._destroy (net.js:613:3)
at Socket.destroy (internal/streams/destroy.js:37:8)
at afterWriteDispatched (internal/stream_base_commons.js:78:17)
at writeGeneric (internal/stream_base_commons.js:73:3)
at Socket._writeGeneric (net.js:713:5)
at Socket._write (net.js:725:8)
I don't think you can re-use the existing client connection to connect again. Therefore, you'll want to wrap it all in a nice closure/function that you can call again to create a new socket and connect.
Try something like this:
var net = require('net');
var HOST = '40.14.121.178'
var PORT = 12537;
var byteToSend = [0x56, 0x34, ...]
function connect() {
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write(byteToSend);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
connect();
});
}
connect();
If I understood correctly, you want to keep your server enabled for requests for a sort amount of time without waiting for 3-way handshake etc. To do that you should use the keep-alive attribute like this.
const net = require('net');
const HOST = '40.14.121.178'
const PORT = 12537;
const byteToSend = [0x56, 0x34, ...];
const server = net.createServer(client => {
client.setKeepAlive(true, 60000); // milliseconds.
client.on('data', data => {
console.log(`DATA: ${data}`);
client.destroy();
});
client.on('end', data => {
console.log('Connection closed');
});
client.on('connect', data => {
client.write(byteToSend);
});
client.on('error', err => {
console.log(`Error: ${err.message}`);
})
});
server.listen(PORT, HOST, () => {
console.log("server started");
});

Avoid creating onMessage function per WS client

Following ws's instructions to create a WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
An onMessage callback named incoming is created for every client, am I right?
Imagine having two million clients. This code would create two million functions. Is there a way to avoid this? Something like this would be wonderful:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('message', function incoming(ws, message) {
// Access to ws object
console.log('received: %s', message);
});
How about:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
function handleMessage(message) {
console.log('received: %s', message);
}
wss.on('message', handleMessage);

How to send broadcast to all connected client in node js

I'm a newbie working with an application with MEAN stack. It is an IoT based application and using nodejs as a backend.
I have a scenario in which I have to send a broadcast to each connected clients which can only open the Socket and can wait for any incoming data. unless like a web-browser they can not perform any event and till now I have already gone through the Socket.IO and Express.IO but couldn't find anything which can be helpful to achieve what I want send raw data to open socket connections'
Is there any other Node module to achieve this. ?
Here is the code using WebSocketServer,
const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
Now, my query is when this code will be executed,
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
Try the following code to broadcast message from server to every client.
wss.clients.forEach(function(client) {
client.send(data.toString());
});
Demo server code,
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 2055 },()=>{
console.log('server started')
})
wss.on('connection', (ws) => {
ws.on('message', (data) => {
console.log('data received \n '+ data)
wss.clients.forEach(function(client) {
client.send(data.toString());
});
})
})
wss.on('listening',()=>{
console.log('listening on 2055')
})

ng-websocket and ws: client sends successfully but doesn't receive

My angularjs client websocketserver can properly send to the server, but when sending from server to client, the client doesn't register the event.
I'm using angular-websockets at the client side and ws at my express.js server
Here's my code.
server
var port = process.env.PORT || 3002;
var server = http.createServer(app); // app = express
server.listen(port);
var socketComs = require('./lib/socketcoms').connect(server);
var connect = function(server) {
var wss = new WebSocketServer({
server: server
});
wss.on('connection', function(ws) {
console.log("websocket connection open");
ws.on('message', function incoming(message) {
console.log('received', message); // THIS WORKS FINE
});
var id = setInterval(function() {
ws.send('pong', 'data 123', function(err) {
console.log('sent pong', err); // THIS IS NEVER CAUGHT BY CLIENT, err = clean
});
}, 2000); // Pong is never received
});
};
client
var connect = function() {
ws.$on('$open', function() {
console.log('wow its working');
ws.$emit('message', 'some message');
});
ws.$on('pong', function(data) {
console.log('yes', data);
});
ws.$on('$close', function(data) {
console.log('wss closed');
});
};
Can anyone see what's going wrong?
I'm using ng-websocket with PHP socket, and I have the same issue.
I just opened the ng-websocket.js and..guess what? the "ping" and "pong" events don't exist!
The "incoming" event is called "$message"...
This is how to get data from server:
ws.$on('$message', function (response) {
console.log("DATA FROM SERVER", response);

Categories