javascript - Using Socket.IO from Node.js to connect to external server -
background: have node.js server running on localhost (call server a); , external server running node.js @ https://example.net:3000 (call server b). not control or have access server b (it dashboard site iot device in home), need connect using socket.io , emit specific message.
i can connect flat javascript file (client-side), need running server side (ultimate goal make can call http request); , examples such how connect 2 node.js servers websockets? suggest should able use socket.io-client node.js same code achieve same results. when run code node.js, cannot connect socket.
below code works in flat javascript file. know works because see 'socket connect' in console, , can test the socket emit @ end.
var myemail = "email@gmail.com"; var device_id = '12345'; // create socketio instance, connect var socket = io.connect('https://example.net:3000'); socket.on('connect', function(){ try { console.log('socket connect'); socket.emit('configure', {email:myemail, deviceid:device_id}); } catch(e) { console.log(e); } }); socket.emit("/" + device_id, "45678");
...and below code cannot work when running node.js instance. i'd expect message 'socket connect' in command line log , nothing.
var express=require('express'); var http=require('http'); var app=express(); var server = http.createserver(app); //variables var myemail = "email@gmail.com"; var device_id = '12345'; var io = require('socket.io-client'); var socket = io.connect('https://example.net:3000'); //connect listener socket.on('connect', function(){ try { console.log('socket connect'); socket.emit('configure', {email:myemail, deviceid:device_id}); } catch(e) { console.log(e); } }); socket.emit("/" + device_id, "45678");
any ideas?
update
ran debug utility, results included linked image below. key thing see engine.io tries xhr poll, , gets 503 response server. (obviously not true 'temporary error' server again, works running client-side js in chrome).
i think line causing issue :
var socket = io.connect('https://example.net:3000');
i managed make working example using code :
const myemail = "email@gmail.com"; const device_id = '12345'; var socket = require('socket.io-client')('https://example.net:3000'); socket.on('connect', function(){ try{ console.log('socket connect'); socket.emit('configure', {email:myemail, deviceid:device_id}); }catch(e){ console.log(e); } });
Comments
Post a Comment