Create WebSockets between a TCP server and HTTP server in node.js - node.js

I have created a TCP server using Node.js which listens to clients connections.
I need to transmit data from TCP server to HTTP server again in Node.js possibly through a Websocket (socket.io).
However, I do not know how to create such connection such that TCP server is able to push data to HTTP server through Websocket.
Many Thanks.

I was trying lot of things to get this work. Most of the time I was relying on socket.io to get this working, but it was just not working with TCP.
However, net.Socket suffices the purpose.
Here is the working example of it.
TCP Server
var net = require('net');
var HOST = 'localhost';
var PORT = 4040;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1");
console.log('Server listening on ' + server.address().address +':'+
server.address().port);
}).listen(PORT, HOST);
HTTP Server
var http = require('http').createServer(httpHandler),
fs = require("fs"),
wsock = require('socket.io').listen(http),
tcpsock = require('net');
var http_port = 8888;
var tcp_HOST = 'localhost';
var tcp_PORT = 4040;
/**
* http server
*/
function httpHandler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function (socket) {
var tcpClient = new tcpsock.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function() {
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data) {
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data) {
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message) {
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
Browser Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
</script>
This way, there is a socket opened between HTTP server and TCP server in Node.js.

If you need to communicate server-server than websockets is probably not a best choice. Try one of RPC libraries, or just use HTTP or your own protocol.

You can use either socket.io or ws (only WebSocket) on Node.js as client (not only in browser)
var io = require('socket.io-client');
var socket = io.connect('http://IP address of Websocket server');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});

Related

Forward Android TCP Connection to HTTP proxy in Node.js

My plan is to create a proxy of my phone 4g connection.
I've made a direct tcp connection of my phone to my pc via nodejs.
I create a client.js on my phone and server.js on my pc. They connect.
Now i need to 'transform' this direct connection into a proxy, but i dont know how.
Any help i would aprecciate.
I will show my server.js and client.js code below.
Server.js
var net = require('net');
var tcpServerPort = 7000;
// a simple TCP server for testing
var server = net.createServer(function (socket) {
console.log('Client connected to server');
socket.on('close', function () {
console.log('Client disconnected from server');
});
socket.on('data', function (buffer) {
// 'echo' server
socket.write(buffer);
});
socket.on('error', function (err) {
console.log('Error: ' + err.soString());
});
});
server.listen(tcpServerPort);
Client.js
const net = require('net');
const client = new net.Socket();
const port = 7000;
const host = 'my home ip';
client.connect(port, host, function() {
console.log('Connected');
client.write("Hello From Client " + client.address().address);
});
client.on('data', function(data) {
console.log('Server Says : ' + data);
});
client.on('close', function() {
console.log('Connection closed');
});

how to test a tcp server of nodejs

I created a simple tcp server using code
var net = require('net');
// Setup a tcp server
var server = net.createServer(function (socket) {
socket.addListener("connect", function () {
console.log('hello');
sys.puts("Connection from " + socket.remoteAddress);
socket.end("Hello World\n");
});
});
server.listen(7000, "127.0.0.1");
console.log("TCP server listening on port 7000 at 127.0.0.1");
It started successfully, but how can I send some test msg to that tcp server, I tried SocketTest v.3 but not console output.
Use data event handler to receive data in the server.
socket.on('data', function(data) {
console.log(data);
// echo back
socket.write('You said '+data);
});
For people still looking for answers, here's how I did it with SocketTest
const net = require('net');
const client = new net.Socket();
const HOST = "127.0.0.1";
const PORT = 7000;
client.on('data', () => {
client.destroy(); // kill after response
});
client.on('error', () => {
client.destroy(); // kill
});
client.connect(PORT, HOST, () => {
client.write('Hello world!');
client.end();
});

NodeJS help proxy TCP port data to web socket

I'm trying to proxy json data from a private TCP port 13854 to a public web socket on port 8080. Why can't I get any data when browsing http://localhost:8080?
var http = require('http').createServer(httpHandler),
fs = require("fs"),
wsock = require('socket.io').listen(http),
tcpsock = require('net');
var proxyPort = 8080;
var serviceHost = 'localhost';
var servicePort = 13854;
function httpHandler (req, res) {
res.setHeader("Access-Control-Allow-Origin", "http://example.com");
res.end();
}
http.listen(proxyPort);
console.info("HTTP server listening on " + proxyPort);
wsock.sockets.on('connection', function (socket) {
var tcpClient = new tcpsock.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(servicePort, serviceHost, function() {
console.info('CONNECTED TO : ' + serviceHost + ':' + servicePort);
tcpClient.on('data', function(data) {
data = "" + data
//send format request to socket
if (data[0] != '{'){
s.write(JSON.stringify({
enableRawOutput : false,
format : "Json"
}) + "\n");
return;
}
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data) {
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message) {
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
THANKS!
First of all, change the line
res.setHeader("Access-Control-Allow-Origin", "http://example.com");
to
res.setHeader("Access-Control-Allow-Origin", "*");
Because you are browsing to localhost, your request will be rejected because the origin is not http://example.com.
Secondly, in order to receive data, you must setup a web socket connection from the client. Just browsing to http://localhost:8080 creates an http connection and not a web socket connection.
I propose to create an HTML page locally and use that by double-clicking on it (instead of going through your server); later you can host the page on your node.js server.
Look at the examples on http://socket.io to correctly create a socket.io client.
I solved the problem by reorganizing my code and keeping the sockets separated. For whatever reason, it seems that Access-Control-Allow-Origin is not needed. I am using a Chrome plugin called "Simple Web Socket Client" to get around needing to write my own client.
var ws = require("nodejs-websocket"),
net = require("net");
var server = ws.createServer(function(conn) {
conn.on("close", function(code, reason) {
console.log("Connection closed");
});
}).listen(8080);
var tcp = new net.Socket();
console.log('connecting to 127.0.0.1:13854');
tcp.connect(servicePort, '127.0.0.1', function() {
//this socket requires sending data on connection
tcp.write(JSON.stringify({
enableRawOutput: false,
format: "Json"
}) + "\n");
});
tcp.on("data", function(data) {
if (server == null || server.connections == null) {
return;
}
//broadcast message:
server.connections.forEach(function(conn) {
conn.sendText(data);
});
}

How to receive log from SRCDS in node.js

I have srcds (source dedicated server)
at console add logaddress_add 0.0.0.0:25001
this turn on sending the log to the remote server
tried to catch the log in this way
var net = require('net');
var server = net.createServer(function(c) {
c.on('end', function() {
console.log('server disconnected');
});
c.pipe(c);
});
server.listen(25001);
and that
var net = require('net');
var client = net.connect({port: 25001});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
and that
var s = dgram.createSocket('udp4');
s.bind(25001, function(data) {
console.log(data)
});
no result. can someone help?
thanks in advance
[solved]
at SRCDS server
logaddress_add 0.0.0.0:8006 //for local ip
at app.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4');
server.on('message', function (message, rinfo) {
var msg = message.toString('ascii').slice(5,-1);
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8006);
I ended up writing a little library to do this (srcds-log-receiver), which validates the packet format, extracts out the date and allows you to use the sv_logsecret function to put a small amount of authentication on the connection, since UDP packets are easily forged.
I also wrote a parser to turn those log lines in to useful objects.

node.js listen for UDP and forward to connected http web clients

I'm new to node.js, so forgive the ignorance if this is simple.
What I want to do is setup a simple node.js http server to which a web-client connects. I also want the node.js server to act as a UDP listener on a separate port, on which it will receive JSON payloads from some other application. I want the node.js server to then forward these JSON payloads immediately to one or more of the connected web-clients.
I got this far from some initial googling around:
Create a simple node.js http server that responds with a static html page:
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: 127.0.0.1 8080');
}
);
Initialize a UDP server on a separate port:
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.broadcast.emit('message', 'test');
//stream.write(msg);
//socket.broadcast.emit('message',msg);
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.bind(5555);
Use socket.io to establish a live connection between web-client and server:
//this listens for socket messages from the client and broadcasts to all other clients
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg.data.skeletons[0] ? msg.data.skeletons[0].skeleton_id : '');
socket.broadcast.emit('message', msg);
}
);
});
I guess my problem is I don't know how to bridge 2 and 3, to get the received UDP packets broadcasted to the connected socket.io clients. Or perhaps there's a simpler, more elegant way of doing this? I found the documentation for socket.io to be lacking...
EDIT: thanks to the person that fixed the code formatting
I made a running example for you to get going with: http://runnable.com/UXsar5hEezgaAACJ
For now it's just a loopback client -> socket.io -> udp client -> udp server -> socket.io - > client.
here's the core of it:
var http = require('http');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/index.html');
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
}).listen( process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP, function() {
console.log('Listening');
});
var io = require('socket.io').listen(server);
io.set('log level', 0);
io.sockets.on('connection', function (socket) {
socket.emit('message', 'connected');
socket.on('message', function (data) {
console.log(data);
var address = srv.address();
var client = dgram.createSocket("udp4");
var message = new Buffer(data);
client.send(message, 0, message.length, address.port, address.address, function(err, bytes) {
client.close();
});
});
});
var dgram = require('dgram');
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.emit('message', 'udp');
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.on('error', function (err) {
console.error(err);
process.exit(0);
});
srv.bind();

Resources