0

This is the first time I'm using Socket.io. I have a chat app that I created on two different files; server.js and pi.js, each that are being hosted on two differnet ports (server on 3000, pi on 3001). I'm referring to https://socket.io/get-started/chat/ as a guide. See below (note there a lot of modules in this file; I've built a web app that serves a separate purpose so most of them can be ignored in this case):

server.js

const express = require('express'),
  app = express(),
  port = process.env.PORT || 3000,
  mongoose = require('mongoose'),
  pug = require('pug'),
  router = express.Router(),
  User = require('./api/models/userAPIModel'),
  bodyParser = require('body-parser'),
  path = require('path'),
  cool = require('cool-ascii-faces'),
  pg = require('pg'),
  http = require('http').Server(app),
  io = require('socket.io')(http),
  request = require('request');

app.get('/theTest', function(req, res){
  res.sendFile(__dirname + '/views/index.html');
});

var clients = 0;

io.on('connection', function(socket) { //on connection, it will show up in the console, and vice versa.
  clients++;
  console.log('User connected. Clients currently connected: ' + clients);

  socket.on('chat message', function(msg) {
    console.log('message: ' + msg);
    io.sockets.emit('chat message', msg); 
  });

  socket.on('disconnect', function() {
    clients--;
    console.log('user disconnected');
  });
});

http.listen(3000, function() {
  console.log('listening on *:3000');
});

My HTML file:

<!doctype html>
<html>

    <head>
        <title>Socket</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font: 13px Helvetica, Arial; }
            form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
            form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
            form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
            #messages { list-style-type: none; margin: 0; padding: 0; }
            #messages li { padding: 5px 10px; }
            #messages li:nth-child(odd) { background: #eee; }
        </style>    
    </head>

    <body>
        <ul id="messages"></ul>
        <form action="">
            <input id="m" autocomplete="off" /><button>Send</button>
        </form>

        <script src="/socket.io/socket.io.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
        <script>var socket = io();</script>
        <script>
        $(function () {
            var socket = io();

            $('form').submit(function() {
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
            });

            socket.on('chat message', function(msg){
            $('#messages').append($('<li>').text(msg));
            });
        });
        </script>
    </body>

</html>

And then my other file (which I have called pi.js), which I have hosted on port 3001 and am hoping to be able to use it to communicate with port 3000, which is not working:

const app = require('express')(),
  http = require('http').Server(app),
  io = require('socket.io')(http);

app.get('/theTest', function(req, res){
  res.sendFile(__dirname + '/views/index.html');
});

// io.connect('http://localhost:3000');

    var clients = 0;

    io.on('connection', function(socket) { //on connection, it will show up in the console, and vice versa.
      clients++;
      console.log('User connected. Clients currently connected: ' + clients);

      socket.on('chat message', function(msg) {
        console.log('message: ' + msg);
        io.sockets.emit('chat message', msg); 
      });

      socket.on('disconnect', function() {
        clients--;
        console.log('user disconnected');
      });
    });


    http.listen(3001, function() {
      console.log('listening on *:3001');
    });

When I test this, server.js and pi.js isn't communicating the way I want it to as when I open up both of the apps, I can enter in a message on one of them but it will not show up on the other. When I have one of the files opened up in two different tabs they are able to communicate with each other. However, I assume that because the HTML document has the script tag connecting with port 3000 then they should be able to communicate. What am I doing wrong here?

Alex Marvick
  • 144
  • 1
  • 2
  • 16
  • why do you need it to be different port? So, you want two different site to communicate each other? – Hatjhie Aug 01 '17 at 03:56
  • @Alex Marvick Why you are running it on two different ports? What is the point of using two different file? You can handle multiple clients with same file – mehta-rohan Aug 01 '17 at 03:57
  • @Hatjhie This was something I was assigned to figure out - I'm not entirely sure of the significance of it either because, Rohan, you're right - I need only one server to handle multiple clients. I think I'm ultimately trying to link two different sites – Alex Marvick Aug 01 '17 at 04:09
  • @mehta-rohan refer to above comment – Alex Marvick Aug 01 '17 at 04:10
  • Please back up and describe the actual assignment here. socket.io allows a client and a server to communicate with a persistent 2-way communication channel. You can have N different clients all establishing their own communication channel with the server, but each communication channel is between a client and the server. If you want one of these clients to use the server as a gateway to then connect to something else, you have to write your own glue to take a message from client A and then send it to some other connection. socket.io does not do that for you in any way. – jfriend00 Aug 01 '17 at 04:19
  • With socket.io event emitted through html bound to server with port(3000) can't listened at html bound with port(3001). – mehta-rohan Aug 01 '17 at 05:13
  • Below link provides you with some idea. https://stackoverflow.com/questions/8837236/how-to-connect-two-node-js-servers-with-websockets – mehta-rohan Aug 01 '17 at 10:23
  • Hey - sorry for the late reply. @jfriend00 I'm linking this up with a raspberry pi and was able to find the solution. What I ended up doing: In the html file, changing the script tag with var socket = io() and put http://localhost:3000 in it In my pi.js file, minified the code so it only has the modules (app, http and io), the get route and the port activation for port 3001 (http.listen(3001, function...)) – Alex Marvick Aug 02 '17 at 17:46

1 Answers1

0

My opion: Because you lack of intermediate side that will connect 2 each other. I suggest you try to use redis.In your case, redis on between (like server), when clinet1 send message (subcrise) on redis, redis will find and reponse cli1's message to client2 (publish). But rememeber unsubcrise when user offline

JohnDe.m
  • 1
  • 1
  • 2