简体   繁体   中英

MultiClient Socket.io/Node.js

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);
    });
});

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM