Alt*_*ime 4 node.js express socket.io
试图在 socket.io 中执行最简单的有针对性的消息传递,但没有成功。根据socket.io with express.js的文档,您可以将消息定位到单个用户套接字socket.to(socket.id).emit('event name', 'message')
我已经从头到尾阅读了socket.io 文档以及其他堆栈溢出 Q/A此处、此处和此处。我发现的一些解决方案涉及创建房间和向这些房间发送消息,但这个问题的目的是使用socket.to(socket.id).emit('event name', 'message')socket.io 文档中给出的方式向套接字 ID 发送消息。
我正在使用 node v6.11.2、express 4.15.2 和 socket.io 2.0.3。
客户端和服务器代码几乎是逐字从https://socket.io/get-started/chat/ 获取的,在我进行实验时做了一些细微的改动。
索引.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
io.on('connection', function(socket){
console.log(req.ip+' connected');
socket.on('chat message', function(msg){
console.log(socket.id);//logs the socket id. Something like 'AUCyM1tnpinCfvfeAAAB'
console.log(msg);//logs whatever the message was, so I know the server is receiving the message
socket.to(socket.id).emit('chat message', 'Nothing is happening here.');
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Run Code Online (Sandbox Code Playgroud)
索引.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
...
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
改变这个:
socket.to(socket.id).emit(...)
Run Code Online (Sandbox Code Playgroud)
对此:
socket.emit(...)
Run Code Online (Sandbox Code Playgroud)
这是一个解释。 socket.to(socket.id).emit(...)将广播到名为 的房间socket.id。没关系,有一个叫这个名字的房间,而且socket是唯一的成员。但是,socket.to()发送给该房间的所有成员,除非socket没有人可以将其发送给。
因此,如果您只想发送到socket,那么只需使用socket.emit().
这是socket.io 文档中socket.to()的一段引用:
为随后的事件发射设置一个修饰符,该事件将只广播给加入给定房间的客户端(套接字本身被排除在外)。
改变这一点:
socket.to(socket.id).emit('chat message', 'Your message');
Run Code Online (Sandbox Code Playgroud)
对此:
io.to(socket.id).emit('chat message', 'Your message');
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以查看此链接:https : //socket.io/docs/emit-cheatsheet/
| 归档时间: |
|
| 查看次数: |
6502 次 |
| 最近记录: |