socket io mouse click event

2019-02-19 09:42发布

问题:

Does anyone know how to listen to the mouse events such as CLICK or HOVER so that when I click or hover any element it will happen the same in the second browser? Apologies for not including the code.

<script>
    // creating a new websocket
    var socket = io.connect('http://localhost:8000');

    // on message recived we print the new data inside the #container div
    socket.on('notification', function (data) {
        $("p").click(function () {
            alert("Hello");
            //or change the color
            $(this).css({"color": "red"});
        });

        var usersList = "<div id='aaa'>";
        $.each(data.users, function (index, user) {
            usersList += "<p>" + user.users + "</p>";
        });

        usersList += "</div>";
        $('#container').html(usersList);
    });
</script>
<p>Click me!</p>

回答1:

Client side:

In client side, you should first define an event listener for every type of event you need (using jQuery). In that listener, simply emit an socket.io event containing ID of element that triggered the event, so server can broadcast that to all other clients.

Also, if an event received from server, you should simulate that on it's corresponding element via jQuery.

$(document).on('click', function(event){
    socket.emit('myClick', {id: event.target});
}

var socket = io.connect('http://localhost');

socket.on('myClick', function (data) {
    $(data.id).trigger('click');
}

Server side:

In server side, just emit whatever event that was triggered, to all other clients except sender.

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
    socket.on('myClick', function (data) {
        socket.broadcast.emit('myClick', data);
    });
});