I am trying to make a console based node.js application which simulates 1000/+ clients Connections to an existing node.js based TCP server app.
Update: With the current version of this code^ I am getting an error TypeError: cannot call method 'write' of undefined at: connx[connNos].Write(str). I guess I will have to rethink/rewrite this piece of code; any pointers are welcome.
Till now this is what I came up with but this doesn't work as implied:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 7000;
var timeout = 30000;
var connx = [];
for(var connNos = 0; connNos < 10; connNos++){
connx[connNos] = net.createConnection(PORT,HOST);
//connx.push(connx[connNos]);
connx[connNos].on('connect', function(err){
console.log('Client: Connected');
});
connx[connNos].on('error', function(data){
console.log('>> ' + data);
});
connx[connNos].on('close', function(){
console.log('Client: Conn Closed');
process.exit();
});
process.stdin.on('data', function(data){
console.log('sending data..');
//connection.write(data);
var str = "486229^4049^1018436^D^2013-04-01 00:02:09^22.715939100^88.374148220^27238^0^308^0^192.168.1.1^1^2013-04-01 19:49:04";
connx[connNos].write(str);
//connection.end();
});
process.stdin.resume();
}
Any help will be appreciated
TIA :D
From the doc
net.createConnection(options, [connectionListener])#
Constructs a new socket object and opens the socket to the given location. When the socket is established, the 'connect' event will be emitted.
For TCP sockets, options argument should be an object which specifies:
port: Port the client should connect to (Required).
host: Host the client should connect to. Defaults to 'localhost'.
localAddress: Local interface to bind to for network connections.
For UNIX domain sockets, options argument should be an object which specifies:
path: Path the client should connect to (Required).
I guess
connx[connNos] = net.createConnection(PORT,HOST);
should be
connx[connNos] = net.createConnection({port:PORT,host: HOST});
Think async, most probably reason is that when you call socket.write socket connection was not estanblished. You should check connection before call or you can put code in connection listener.
Related
I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above
I am trying to make a proxy between sockets and websockets. I receive requests on socket server and I want to proxy them to websocket clients, however websocket.ws.send appears to be undefined. What would be the correct way of doing this? How to call ws.send() from outside of the object?
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8001}),
var net = require('net')
websocket = wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send("NEW USER JOINED");
});
var socketServer = net.createServer(function(socket) {
socket.on("data", function(data){
console.log("Received: "+data)
websocket.ws.send("Message")
});
});
socketServer.listen(1337, '127.0.0.1');
The problem you have is that ws is a single web socket for one connection. It is not a property on the websocket object, but an argument to a callback you define. Each time someone connects you will get a connection event which will execute your callback, allowing you to bind a function to that specific web socket for the message event.
You either need to store the ws object in a variable that the socket server can access or you could broadcast to all clients.
wss.clients.forEach(function each(client) {
client.send(data);
});
This will work fine if you only have one client, however if you have multiple connections to both the websocket and socket server then you need to use a method of identifying connections on both so that you can locate the websocket connection you need to send data to.
I'm trying to push messages from server to client using ws module in node.js application.
Please find below the code in app.js.
var server = app.listen(port);
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({ server: server});
wss.on('connection', function (ws) {
console.log('connected');
});
ws.on('message', function (data, flags) {
});
});
code in the client side js file.
window.WebSocket = window.WebSocket || window.MozWebSocket;
var host = window.document.location.host.replace(/:.*/, '');
var port = window.document.location.port;
var socketConnection = new WebSocket('ws://'+ host+':'+ port);
socketConnection.onerror = function (error) {
// TODO : report error here..
};
socketConnection.onmessage = function (message) {
var obj = JSON.parse(message.data)
};
The problem is when i'm running the node application locally.i.e http://localhost:port and when I try to handshake with ws connection through "ws://localhost:port\". The handshake happens and i am able to send and receive messages.
But when i access the same application using the ip of my machine i.e as http://10.xx.yy.zz:port. Im able to open the application and do evrything but the handshake with websockets time out. The same happens when the app is running in another machine and i try to connect to it from my machines browser.The handshake doesnot happen and it times out.
I have tried the same with demos provided out of box by ws module. The same happens. Am I missing something when creating the websocket server?
I'm trying to test out Node.js and I'm using this code:
// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
// Every time someone connects, tell them hello and then close the connection.
socket.addListener("connect", function () {
//sys.puts("Connection from " + socket.remoteAddress);
console.log("Person connected.");
var myPacket = [1,2,3,4,5];
sys.puts(myPacket);
socket.end("Hello World\n");
});
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");
To send a byte array to any connections that show up on port 7000 of local host. Nothing is connecting though, I've tried firefox (localhost:7000, and 127.0.0.1:7000) I tried PuTTy, and even writing my own Java TCP Client to connect to local host, but nothing is working, so I'm convinced that the code is wrong.
Can someone please tell me why my code won't allow connections?
You seem to be overcomplicating the connection part. The callback with the socket is already the connection event so you don't need to listen to it separately. Also, if you want to send binary, use the Buffer class. Here's your code changed. Remember to set your mode to telnet in putty when connecting. I've also changed the end() to write() so it doesn't auto close the connection.
// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
//sys.puts("Connection from " + socket.remoteAddress);
console.log("Person connected.");
var myPacket = new Buffer([65,66,67,68]);
socket.write(myPacket);
socket.write("Hello World\n");
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");
node.js WebSocket example code snippet
I have a simple node.js application using express. Now everytime a client connects to the node server I see the string 'new client connected' but I would like to know which IP the new client had.
var WebSocketServer = require('ws').Server;
var connIds = [];
var server = require('http').createServer(app).listen(80);
// set up the websocket server
var wss = new WebSocketServer( { server: server } );
wss.clientConnections = {};
// websocket server eventlisteners and callbacks
wss.on('connection', function (connection) {
console.log('wss.on.connection - new client connected');
...
See the code at:
https://github.com/qknight/relais.js/blob/master/relais.js/server.js#L159
question
The object connection has properties but I don't understand how to query them or what they are. All I want is to print the client IP and maybe, if existent, other similar properties as well.
How do I do that?
Remote IP is a property of the pre-upgrade connection:
var wss = new WebSocketServer({port: 9876});
wss.on('connection', function(ws) {
console.log(ws.upgradeReq.connection.remoteAddress);
});
i don't recall how i found it, but i know it took me a while; i wish the docs were as good as the code...
UPDATE:
WS has moved some things around, so here's an updated example of how to get the original HTTP info in current code. Note the 2nd argument to the connection event handler:
wss.on('connection', function conn(ws, req) {
var ip = req.connection.remoteAddress;
console.info(ip);
});