3

I'm trying to use Socket.IO to send data between two Node.JS servers. I usually only use Socket.IO for Node.JS to/from a website, but I've never gone server to server. How can I do this? I really only need to know how a Node.JS server can create that connection to another Node.JS server.

Side note: If there's a better/easier way of sending data from server to server, please do let me know. Both servers are hosted at the same IP.

APixel Visuals
  • 1,508
  • 4
  • 20
  • 38

1 Answers1

4

You get the socket.io-client module for node.js and use pretty much the same code with it that you would use from a browser to connect to another socket.io server.

You can see an example of server-side usage of socket.io-client here in the socket.io doc.

var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you so much! This is exactly what I was looking for. – APixel Visuals Jul 07 '18 at 02:40
  • Is there an equivalent of this for the ws library? – Normajean Jun 06 '21 at 03:32
  • @Normajean - Depending upon which server-side webSocket library, some have client-side webSocket support built in. This [ws library](https://www.npmjs.com/package/ws) has client-support already built in. – jfriend00 Jun 06 '21 at 04:04
  • how do I use it? I tried shoving the client-side code in one node js server and then the server side code in another server but it doesn't seem to work..? – Normajean Jun 06 '21 at 04:14
  • @Normajean - If you want further help with that, please write your own question and show the code you tried (both client and server code). Nobody can help you without seeing the code. Your question is not really related to this socket.io question. – jfriend00 Jun 06 '21 at 04:15
  • I would but stackoverflow says if I write another question they'll ban me – Normajean Jun 06 '21 at 04:15
  • but am I basically on the right track? I just use the client side code and put it in the server? and then use the server side code and put that in the second server? – Normajean Jun 06 '21 at 04:16
  • @Normajean - Yes, that's the basic concept. It's identical to an http server and an http client request - they are both done with functions in the nodejs http library. Let's not do this any more here. – jfriend00 Jun 06 '21 at 04:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/233368/discussion-between-normajean-and-jfriend00). – Normajean Jun 06 '21 at 04:18