Skip to content

Instantly share code, notes, and snippets.

@MustansirZia
Last active April 12, 2017 09:04
Show Gist options
  • Save MustansirZia/a2778a610998dea85b7758ba8d48576d to your computer and use it in GitHub Desktop.
Save MustansirZia/a2778a610998dea85b7758ba8d48576d to your computer and use it in GitHub Desktop.
A TCP server written in NodeJS (ES5) that carries data from TCP clients to Deepstream.
'use strict';
/**
* Created by M on 11/04/17. With ❤
*/
// The Job of this server is to listen for tcp connections on port 3000
// and then to transmit data coming from a tcp client to Deepstream (https://deepstream.io/)
// I made this gist so people could use the language of their choice for Deepstream. (Since Deepstream clients are only available for JavaScript and Java)
// I'm currently using Go-lang as the server side language and need to push events on Deepstream. Thus, the gist!
// Corrections are welcome!
// Acquire the Deepstream client and net package from dependencies.
const deepstream = require('deepstream.io-client-js');
const client = deepstream('localhost:6020');
const net = require('net');
const dsClient = client.event;
// Variable to keep track of Deepstream client connection status.
var dsConnected = false;
// If connection to deepstream ever breaks down, we'd know about it. Plus Vice Versa!
client.on('connectionStateChanged', function (state) {
switch (state) {
case deepstream.CONSTANTS.CONNECTION_STATE.ERROR:
dsConnected = false;
console.warn('Deepstream Disconnected');
break;
case deepstream.CONSTANTS.CONNECTION_STATE.OPEN:
dsConnected = true;
console.log('Deepstream Connection Successful | NodeJS client ready.');
break;
}
});
// Explicit DS error handling.
client.on('error', function (error, event, topic) {
console.warn('Deepstream Error | msg: ' + error + ' | event: ' + event + ' | topic: ' + topic);
});
// Where we initialize our tcp server which would run at 3000 shortly.
const tcpServer = net.createServer(function (socket) {
// Callback called when a tcp connection sends data (as bytes) to our DS Client.
socket.on('data', function (data) {
// Parse data byte array to JSON object.
// Byte Array after conversion to String should look like this:
// "{ eventName: "deepstream-event-name", payload: "data to send (could be another stringified JSON!)" }"
try {
const deserialized = JSON.parse(data.toString());
if (dsConnected) {
// Emit to Deepstream if Deepstream client is connected.
dsClient.emit(deserialized.eventName, deserialized.payload);
// Send success response to tcp client.
sendResponseToTCPSocket(null, socket);
} else {
// If Deepstream is not connected, try to reconnect and pass a callback.
// Callback to be called if re-connection occurs or if the reconnection attempt failed.
connectDSClient(function (success) {
if (success) {
// Resend to Deepstream.
dsClient.emit(deserialized.eventName, deserialized.payload);
// Send success response to tcp client.
sendResponseToTCPSocket(null, socket);
} else {
// Send error response to tcp client.
sendResponseToTCPSocket('Cannot Login to Deepstream', socket)
}
});
}
} catch (err) {
console.warn(err);
sendResponseToTCPSocket('Incorrect Data Format - ' + err.toString(), socket);
}
});
});
// Function to connect to Deepstream.
function connectDSClient(callback) {
// Login as a client.
client.login({username: 'mz', password: 'password'}, function (success, data) {
if (success && callback) {
callback(true);
}
else if (callback) {
callback(false);
}
});
}
// Function which sends response to the tcp client.
// TCP client should close the connection from their end when they get a response.
// '\n' the newline character at the end acts as a delimeter on the other side.
function sendResponseToTCPSocket(err, socket) {
if (!err) {
socket.write('OK\n');
} else {
socket.write('ERR - ' + err.toString() + '\n');
}
}
// Connect to Deepstream for the first time.
connectDSClient();
// Start the TCP server.
tcpServer.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment