我有多个按钮,其中包含一个名为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”
如何实现这一目标?
答案 0 :(得分:1)
似乎你想要一个类似于聊天的东西 - 点击链接就像用户向服务器发送消息一样,服务器会将其发送到一个房间(对于其他用户,我想?)< / p>
如果是这种情况,您应该看一下这个例子: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');
});