socket.io:发射按钮's属性值

socket.io: Emit button's attribute value on click?

本文关键字:属性 io 发射 按钮 socket      更新时间:2024-04-24

我有多个具有groupName属性的按钮。它们看起来像这样:

<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_I">SCENE I</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_II">SCENE II</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_III">SCENE III</a>

我正试图弄清楚如何让socket.io在单击时发出链接的groupName值。因此,当点击第一个链接时,socket.io会发出"groupName-SCENE_I"

如何才能做到这一点?

你似乎想要类似于聊天的东西——点击链接就像用户向服务器发送消息,服务器会将消息发送到房间(我想是向其他用户?)

如果是这样的话,您应该看看这个例子:http://socket.io/get-started/chat/

你可以在客户端做这样的事情:

<html>
<head>
</head>
<body>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_I">SCENE I</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_II">SCENE II</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_III">SCENE III</a>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
  var socket = io();
  // listen to server events related to messages coming from other users. Call this event "newClick"
  socket.on('newClick', function(msg){
    console.log("got new click: " + msg);
  });
  // when clicked, do some action
  $('.fireGroup').on('click', function(){
    var linkClicked = 'groupName - ' + $(this).attr('groupName');
    console.log(linkClicked);
    // emit from client to server
    socket.emit('linkClicked', linkClicked);
    return false;
  });
});
</script>
</body>
</html>

在服务器端,仍在考虑聊天的想法:

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

app.get('/', function(req, res){
  res.sendfile('./index.html');
});
io.on('connection', function(socket){
  // when linkClicked received from client... 
  socket.on('linkClicked', function(msg){
    console.log("msg: " + msg);
    // broadcast to all other users -- originating client does not receive this message.
    // to see it, open another browser window
   socket.broadcast.emit('newClick', 'Someone clicked ' + msg) // attention: this is a general broadcas -- check how to emit to a room
  });
});
http.listen(3000, function(){
  console.log('listening on *:3000');
});