I've modified some code from a simple chat tutorial in a very basic way so that I have a JavaScript chatbot sitting on a NodeJS server which immediately sends a response to the client when the user inputs something.
This is the relevant part of the code on the NodeJS server, which 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's response
io.sockets.emit('updatechat', 'BOT', bot.transform(data));
});
So the bot's response is very much tied up with the user's input. I want to now put the bot on a different node server so that the chat can deliver and react to the bot in the same way as it does the user, and so that the bot can process and act independently. Roughly:
USER (client/browser) <---> MEDIATOR (Node server 1) <---> CHAT BOT (Node server 2)
...
I have tried what seemed to me to be the obvious thing to do (which was also obviously wrong), which is take this line from my client:
var socket = io.connect('http://localhost:8080'); // 8080 being the port for the other server
I dropped this into my server-side js file like so:
var app = require('express').createServer();
var io = require('socket.io').listen(app);
app.listen(8080);
var socket = io.connect('http://localhost:8080');
But this produces an error in the node console to say that the io object has no method connect. Perhaps this is because connect belongs only to the client-side JS script. Is there an easy way for me to have my Node server interact with another Node server without hacking up the client-side library?
More fundamentally, is it even possible to run two node servers at once and have one be a mediator to pass and receive messages from another before pushing to the client? I am using using the Express framework (v2.4.6) and socket.io (v0.8.4), but I'm open to other suggestions.
There are some mistakes in your code. One should 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 the clients. Also you cannot drop the same line from the client on the server !!!, use the following to connect to another server from node.
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 to work. See here: https://npmjs.org/package/socket.io-client
Simply do this for installation npm install socket.io-client