Nodejs , Redis,Sockets - node.js

I have a nodejs app which reads data from redis and I am unable to push it into socket. In the c.write(message) part, if I hardcode(example c.write('hello') ,the messages are being put to the socket but when i put it as c.write(message), nothing is going to the socket. Thanks in advance,
var net = require('net');
var split = require('split');
var Redis = require('ioredis');
var redis = new Redis();
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
redis.subscribe('test-channel');
redis.on('message', function(channel, message) {
console.log(message);
c.write(message);
c.pipe(c);
});
});
server.on('error', (err) => {
throw err;
});
server.listen(3005, 'localhost', () => {
console.log('server bound');
});

I have got the answer.
Just add below lines to your code :
var message_redis = message+'\r'+'\n';
c.write(message_redis);

Related

Multiple socket connection for TCP server, How to scale using worker thread in Nodejs

I have following code, As there are N number of socket sending sequential stream.
how to scale this using worker threads in nodejs.
const Net = require('net');
const port = 8080;
const server = new Net.Server();
const processor = require('processor.js');
server.listen(port, function() {
console.log(`Server listening for connection requests on socket localhost:${port}`.);
});
server.on('connection', function(socket) {
console.log('A new connection has been established.');
let connectionInfo = {};
connectionInfo.id = `${socket.remoteAddress}:${socket.remotePort}`;
connectionInfo.partialBuffer= undefined;
socket.on('data', function(chunk) {
let chunkBuffer = Buffer.from(chunk);
if(connectionInfo.partialBuffer){
chunkBuffer = Buffer.concat([connInfo.partialBuffer, chunkBuffer]);
}
processor.processChunk(connectionInfo, chunkBuffer); // set connectionInfo.partialBuffer in processChunk() function
});
socket.on('end', function() {
console.log('Closing connection with the client');
});
socket.on('error', function(err) {
console.log(`Error: ${err}`);
});
});

How to send multiple data streams from single client to a tcp server

Server Side code
var net = require('net');
var server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log('data received');
console.log('data is: \n' + data);
});
});
var HOST = '127.0.0.1';
var PORT = '8000'
server.listen(PORT, HOST, function() {
//listening
console.log('server is listening to ' + PORT + '\n');
server.on('connection', function(){
console.log('connection made...\n')
})
});
Client Side Code
var client = new net.Socket()
//connect to the server
client.connect(PORT,HOST,function() {
'Client Connected to server'
//send a file to the server
var fileStream = fs.createReadStream(__dirname + '/readMe.txt');
// console.log(__dirname + '/readMe.txt');
fileStream.on('error', function(err){
console.log(err);
})
fileStream.on('open',function() {
fileStream.pipe(client);
});
});
//handle closed
client.on('close', function() {
console.log('server closed connection')
});
client.on('error', function(err) {
console.log(err);
});
I want to know how can we achieve creating a client and a TCP server and sending multiple data from only one client to server.
I know there can be multiple clients that can connect to server that request to server and get response back but I don't want that, I want to know is it possible that a single client can send multiple data streams to a server in node.js.
The thing is suppose there is a file in which 200 lines of chunk data is present so I know we can read that file using createReadStream but suppose there are multiple files which has 200 lines of data (example) so how to send these multiple files over TCP server
Any example would be appreaciated.
Please give an explanation using a example as I am new to node.js
The example above is sending the data of one file to the server, My question what if the client want to send hundreds of files (or any data streams), So how can he send to through a single medium to TCP server ?
This is possible using the net module, the fs module, and a basic forEach construct for looping over the files:
server.js
const net = require('net');
const host = "localhost";
const port = 3000;
const server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log(`data received: ${data}`);
});
});
server.listen(port, host, function () {
console.log(`server is listening on ' + ${port}`);
server.on('connection', function () {
console.log('connection made...\n')
})
});
client.js
const net = require("net");
const fs = require("fs");
const port = 3000;
const host = "localhost";
const files = [
"file1.txt",
"file1.txt",
"file1.txt"
// As many files as you want
]
const client = new net.Socket()
client.connect(port, host, function () {
files.forEach(file => {
const fileStream = fs.createReadStream(file);
fileStream.on('error', function (err) {
console.log(err);
})
fileStream.on('open', function () {
fileStream.pipe(client);
});
});
});
client.on('close', function () {
console.log('server closed connection')
});
client.on('error', function (err) {
console.log(err);
});

socket.io client not receiving message

When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!

how to attach socket.io to SwaggerExpress

I am using swaggerexpress middleware and swagger.
I can't get to work with socket.io
What is the proper way to attach socket.io to my server created?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var io = require('./api/helpers/socketio');
module.exports = app;
var config = {
appRoot: __dirname
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
app.listen(10010, function () {
console.log('Application is start listening on localhost:10010');
});
io.on('connection',function(socket){
console.log("A user is connected: " + socket.id);
io.emit('message', "Welcome")
});
});
io.attach(app);
With that approach, my server is not getting up, got an error on socket.io attaching to app.
If you're okay using a different port for socket.io, you could do something like this:
var io = require('socket.io')(10011);
// Or maybe in your case:
// var io = require('./api/helpers/socketio')(10011);
io.on('connection', function(socket) {
console.log('user connected');
});
On the client you'd connect to it like this:
var socket = io('http://localhost:10011');
socket.on('connect', function() {
console.log('Socket connection established');
});

How to create a simple socket in node.js?

I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
Client only..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
Try this.
The production code app.js:
var net = require("net");
function createSocket(socket){
var s = socket || new net.Socket();
s.write("hello!");
}
exports.createSocket = createSocket;
The test code: test.js: (Mocha)
var sinon = require('sinon'),
assert = require('assert'),
net = require('net'),
prod_code=require('./app.js')
describe('Example Stubbing net.Socket', function () {
it("should say hello on connect", function (done) {
var socket = new net.Socket();
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
console.log(data);
assert.equal("hello!", data);
done();
});
stub.on = socket.on;
prod_code.createSocket(socket);
});
});
We can create socket server using net npm module and listen from anywhere. after creating socket server we can check using telnet(client socket) to interact server.
server.js
'use strict';
const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
insertData(d);
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
}
function insertData(data){
console.log(data,'data');
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('gprs').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
using telnet:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
you need to connect your socket before you can write to it:
var PORT = 41443;
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.connect(PORT, function(){
s.write("hello!");
});
It will useful code for websocket
'use strict';
const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';
const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/', function(req, res) {
res.sendFile(INDEX, { root: __dirname });
});
const server = express()
.use(router)
.use(bodyParser.json())
.use(cors)
.listen(PORT, () => {
console.log(`Listening on ${PORT}`)
});
const wss = new Server({ server });
wss.on('connection', (ws) => {
ws.on('message', message => {
var current = new Date();
console.log('Received '+ current.toLocaleString()+': '+ message);
wss.clients.forEach(function(client) {
client.send(message);
var getData = JSON.parse(message);
var newclip = getData.clipboard;
var newuser = getData.user;
console.log("User ID : "+ newuser);
console.log("\nUser clip : "+ newclip);
});
});
});

Resources