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?
Related
I am making a control panel for my Minecraft mining turtle and I need to communicate between the two using websockets. I have troubleshooted the Lua side of things and that works as intended when I connected it to a echo server.
Code here:
local ws,err = http.websocket("wss://localhost:5757")
if ws then
ws.send("Hello")
print(ws.receive())
ws.close()
end
However, I can not get the NodeJS side to work. I have tried different ports, I've tried opening ports.
Code here:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5757 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('testing 123');
});
I can't figure out where I have gone wrong. All help is appreciated.
EDIT: Thought I'd add that it's not giving errors either, that I am using the ws npm package and running the latest LTS node version.
EDIT 2: I tried this code example here
const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org/');
ws.on('open', function open() {
ws.send('testing 123');
});
ws.on('message', function incoming(data) {
console.log(data);
});
And it worked and replied with 'testing 123' so it seems that the web socket doesn't want to run on local host.
I'm using ws library to handle Websocket connections client-side.
Here's example from ws docs (https://github.com/websockets/ws#usage-examples):
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
The problem is that this program exits after receiving just the first message from server.
How do I make it run and listen for messages indefinitely?
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
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);
});
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.