How to use the net module from Node.js with browserify? - node.js

I want to use the net module from Node.js on the client side (in the browser):
var net = require('net');
So I looked up how to get Node.js modules to the client, and browserify seems to be the answer. I tried it with jQuery and it worked like a charm.
But for some reason the net module does not want to work. If I write require('jquery') it works fine, but if I write require('net') it does not work, meaning my bundled .js file is empty.
I tried to search for something else, but the only thing I found is net-browserify on Github. With this, at least my bundle.js file is filled, but I get a JavaScript error using this (it has something to do with the connect function).
This is my code which works on the server side just fine:
var net = require('net-browserify');
//or var net = require('net');
var client = new net.Socket();
client.connect({port:25003}, function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
I assume that net-browserify lets you use a specific connect function, but I don't know which.
How can I use the net module from Node.js on the client side?

This is because net gives you access to raw TCP sockets - which browsers simply cannot do from the JavaScript end. It is impossible for net to ever be ported to the client side until such an API is written (allowing arbitrary tcp traffic).
Your best bet if you want to send tcp data from the client to the server is using web sockets using the socket.io module or the ws one.
Your best bet if you want clients to communicate directly is to look into WebRTC

Related

trying to connect to TCP server using Node.js

I'm trying to connect to a server/specific port using Node.js, and I don't even get past var net = require('net');
I'm using Node.js v16.15.0.
Welcome to Node.js v16.15.0.
When I use the command above, I receive UNDEFINED. As far as I know, I've installed everything I need (including socket.io), and I'm working within the Node.js environment in iTerm.
My goal is to connect to a TCP server, receive a list of files, and then download each of them over a persistent socket. But I'm a little stuck as I can't even seem to get into the TCP server in the first place.
This is what I think I'm supposed to run to get in (obviously with my correct port and IP info which is omitted below).
var HOST = 'IP';
var PORT = 'PORT'
var FILEPATH = 'myfilepathhereIwilltweakitwhenIgettothispoint';
Can anyone point me in the right direction?
From what you said, I think you are trying to code NodeJS script within the NodeJS executable start in command line. You get an UNDEFINED because you imported the library into your variable and this assignment does have any value, so it is UNDEFINED. You can read more about this in this subject : link
But what we usually do in NodeJS development is creating a file, let's call it index.js. Inside that file we are writing our code, let's say :
const net = require('net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
Code sample from NodeJS Documentation.
Then we want to run our code by using the command line like this : node path/to/index.js.
Hope it helps !

socket.io client side in nodejs app

i am using socket.io for communication between server and client.
My client side is not a html. My client side is javascript file. so here is my code of client side
var io = require('socket.io-client')
var socket = io.connect('http://localhost:3000/home');
socket.on('connect', function () {
console.log(' Connected!');
});
On server side i have received the connection event but on client side connect event doesn't fire. I have tested through html way, it works but why its not working through a java script file.
I have no idea what you mean with tested through html way, but try socket.on("connection", ...),
not "connect".
could be related to the fact that you're specifying a namespace different from the default.
try to handle the connection at http://localhost:3000, instead of http://localhost:3000/home
var socket = io.connect('http://localhost:3000');
found a similar situation here

Connecting to socket.io 1.x manually using websockets, capacity testing

I am working with a nodejs express server which uses socket.io to communicate an iOS client, and am having a little trouble trying to test how many clients can connect and exchange data at any one time.
My goal is to be able to run a script which connects to socket.io with thousands of different sessions, as well as send and receive data to understand our system's scale. Currently we are using a single dyno on Heroku but will likely be considering other options on AWS soon.
I have found code which should do what I am trying to do for earlier versions of socket.io, such as this, but have had issues since it seems v1.x has a very different handshake protocol. I tried out using the socket.io-client package, but trying to connect multiple times only simulates use of one session, I need to simulate many in independent users.
I have been picking apart the socket.io-client code, but have only gotten so far as creating a connection - I am stuck on the sending data part. If anyone has any knowledge or could point to some written resources on how data is sent between a client and a socket.io server, it would help me out a lot.
Here's what I have so far:
var needle = require('needle'),
WebSocket = require('ws'),
BASE_URL = 'url-to-socket-host:5002';
var connectionNo = 0;
needle.get('http://' + BASE_URL + '/socket.io/?EIO=3&transport=polling&t=1416506501335-0', function (err, resp) {
// parse the sid
var resp = JSON.parse(resp.body.toString().substring(5, resp.body.toString().length));
// use the sid to connect using websockets
var url = 'ws://' + BASE_URL + '/socket.io/?EIO=3&transport=websocket&sid=' + resp.sid;
console.log(connectionNo + ' with sid: ' + resp.sid);
var socket = new WebSocket(url, void(0), {
agent: false
});
socket.on('open', function () {
console.log('Websocket connected: ' + connectionNo);
// I don't understand how to send data to the server here,
// from looking at the source code it should use some kind
// of binary encoding, any ideas?
socket.on('message', function (msg) {
console.log(msg);
});
});
});
I will continue deconstructing the socket.io-client code but if anyone has any clues or recourses that may help, let me know. Thanks.
I ended up setting for using the socket.io-client npm package which has the ability to connect to a new session on every connection. I found an example benchmark in this issue.
There is not so much need for me to manually connect to socket.io using pure websockets and HTTP, but thanks to Yannik for pointing out the parser in use. The spec of the inner workings of v1.x can be found here.
Thanks!
The problem my reside in the fact that you are not using socket.io in your client code. You have imported ('ws') which is another module whose docs are here: https://www.npmjs.org/package/ws.
You probably want to ws.send('something');. When you receive a message in ws, it also comes with an object with a property indicating whether it is binary data or not. If it is, you will need to concatenate the chunks incrementally. There is a canonical way to do this which you can find via google. But it looks a little like this:
var message;
socketConnection.on('data', function(chunk){ message += chunk});

Connecting to socket.io server

I'm trying to get this exmaple working on my own computer:
https://github.com/tamaspiros/simple-chat
I have node.js installed and have installed socket.io as well. The readme is informing me to change the IP addresses on these two lines:
var socket = io.listen(1223, "1.2.3.4");
var socket = io.connect("1.2.3.4:1223");
However, I'm not really sure what to change the IP addresses into. I would like to get the simple chat box application working on my own computer.
You just need to configure it in one like, for ie:
var socket = io.connect('adress:port');
where addres is Your socket.io server IP or hostname, and yyyy is port on which it listens.
after that, You can get and emit events with:
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
on server listen for
and thats it.
Before making chat You can try just using this example from official socket.io: link
PS dont forget to add socket.io client file source on client side! :). The whole code should look like in the example in the provided link.

Using Meteor and socket.io together

I am newbie about Meteor.
I am developing a realtime multiplayer game. I want to implement everything about the game but game engine states with Meteor. For example chat messages, available game rooms, invitations, online members etc. I want to make those functionalities withMeteor.
But I want to implement game states manually without Meteor with socket.io. Because, the game is real time and every 45 msec(in my architecture), game states will be streaming to the clients and I think Meteor is not for this and not flexiable. So I developed multiplayer concept and synchronising clients and server with socket.io. There is no problem about it.
I want to use Meteor and socket.io both and together. I tried to implement it. I installed socket.io with npm inside .meteor/local/build/programs/server/app under my meteor app. After that I include require statement on server side Meteor startup;
Meteor.startup(function () {
var require = Npm.require;
var sio = require('socket.io')
var socketIO = sio.listen(this.http)
socketIO.configure(function () {
socketIO.set('log level', 0);
socketIO.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
});
socketIO.set("transports", ["xhr-polling"]);
socketIO.set("polling duration", 30);
});
socketIO.sockets.on('connection', function (client) {
console.log(client.id + ' is connected')
client.on('disconnect', function () {
console.log(client.id + ' is diconnected')
});
})})
And I put the connection statement on client side Meteor startup;
Meteor.startup(function () {
socket = io.connect();
socket.on('connect', function () {
console.log('connecting');
});
})
On client side, io variable is not defined error is occurred. This is seen to me that,Meteor does not import client side socket.io.js on client side. So I tried to put socket.io.js manually under clients folder to load it on client side. This is not good way I know, I should not do this. But, even I do and client loads it, there is another client side error about transport variable of io for the statement;
io.transports.push('xhr-polling');
It says that Uncaught TypeError: Cannot call method 'push' of undefined. Somehow, client side socket.io.js can not be loaded properly.
I could not find an example for usage of Meteor and socket.io together. Is there a simple way to use them both together?
Thank you!

Resources