0

So what I want to do is to make Index (for example) to send messages to Index2, The reason I want to do this is so that I can have two different messaging clients. Is there any way to do this? for example lets say Index is the controller and Index2 is the game.

Here is my code for index and Index2:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    jQuery(function($) {
        var socket = io.connect();
        var $messageForm = $('#send-message');
        var $messageBox = $('#message');
        var $chat = $('#chat');

        $messageForm.submit(function(e) {
            e.preventDefault();
            socket.emit('send message', $messageBox.val());
            $messageBox.val('');
        });

        socket.on('new message', function(data) {
            $chat.append(data + "<br/>");
        });
    });
</script>

Server side:

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

server.listen(3000);

app.get('/:index', function(req, res) {
    res.sendfile(__dirname + '/Index.html', '/index2.html');
});

io.sockets.on('connection', function(socket) {
    socket.on('send message', function(data) {
        io.sockets.emit('new message', data);
    });
});
2
  • You can use "rooms" for that. Look at the socket.io docs. Commented Jul 23, 2014 at 4:54
  • Thanks, I'll give that a try, but can you give me an example? Commented Jul 23, 2014 at 5:22

1 Answer 1

1

As long as you connect the socket to the same place on each client, they will send messages to each other (docs).

var socket = io("https://my.domain.com/shared")

Use rooms / namespaces on the server (docs).

serverio.of('/shared')
Sign up to request clarification or add additional context in comments.

5 Comments

So the var socket = io("my.domain.com/shared") replaces the var socket = io.connect(); on the Index2? Or does it replace on both index and index2? Also where does the "serverio.of('/shared')" go in the app.js file? Thanks
io() is a shortcut for io.connect(). The server io goes in your server javascript (maybe called app.js?)
Hi, Aj Can you show me where to put the two lines of code? Im not exactly sure where in the document to put them, Thanks
Put your code (w/e you have) online somewhere and give a link. More than happy to help.
Thanks for your help AJ! I've figured it out. I'll make sure to show you the finished project!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.