Can two Node servers run concurrently and communicate so that one is an intermediary serving the client?
I changed the code very little from a simple chat tutorial so that I have a JavaScript chatbot sitting on a NodeJS server that immediately sends a response to the client when the user enters something.
This is the relevant piece of code on the NodeJS server that works:
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
// we also tell the client to send the bot response
io.sockets.emit('updatechat', 'BOT', bot.transform(data));
});
Thus, the bot's response is very much related to user input. I want to now put the bot on a different node server so that the chat can deliver and respond to the bot in the same way as the user, and so that the bot can handle and act independently. Roughly speaking:
USER (client / browser) <--->
MEDIATOR (Node server 1) <--->
CHAT BOT (Node server 2)
...
I've tried what seemed obvious to me (which was also clearly wrong), which takes this line from my client:
var socket = io.connect('http://localhost:8080'); // 8080 being the port for the other server
I put this in my server side js file like this:
var app = require('express').createServer();
var io = require('socket.io').listen(app);
app.listen(8080);
var socket = io.connect('http://localhost:8080');
But this throws an error in the node console to say that the object io
has no method connect
. Perhaps this is because it connect
only belongs to the client side JS script. Is there an easy way to get my node server to communicate with another node server without hacking the client side library?
More fundamentally, is it possible to run two node servers at the same time and is there one of the intermediaries to transmit and receive messages from the other before clicking on the client? I'm using Framework Express (v2.4.6) and socket.io (v0.8.4), but I'm open to other suggestions.
source to share
There are some bugs in the code. Need to use
io.sockets.on('connection', function (socket) {
socket.on('updatechat', function(data) {
...
sockets.emit('User',{'user': 'login'});
sockets.emit('User',{'data': data});
});
});
Use socket.emit not io.sockets.emit. io.sockets.emit will send to all clients. Also you cannot drop the same line from client on server !!!, to connect to another server from node use the following:
var ioc = require('socket.io-client'); //ioc
var socket2 = ioc.connect('server2:8080'); //socket2
Rest you can figure out: client -> socket -> server -> socket2 -> server2
Update: socket.io-client is a separate package that needs to be installed for this. See here: https://npmjs.org/package/socket.io-client
Just do it to install npm install socket.io-client
source to share