如何发送套接字.使用socket.userId将io数据传输到特定的客户端



我是socket.io的新成员。我用的是大象。IO和socket。io中,我需要发送一些通知数据到特定的客户端。但我不能用插座。Id是自动生成的Id,我需要使用我的用户Id,所以我怎么能发送数据请给我一个服务器端和客户端。

另一种方法是为每个房间设置不同的事件侦听器,然后发出类似message_${room_id}的内容。

由于您没有提供任何参考代码,下面的代码可能不是特定于您的用例,需要调整。

backend-server.js

// Define variables
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server); 
// room_id generator
function makeid(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
app.get('/request-room', function(req, res) { // Listen for the incoming request to /request/room
let room_id = makeid(20); // Generate a roomID 20 characters long
res.redirect('/rooms/' + room_id); // Redirect the user to the room
});
app.get('/rooms/:roomId', function(req, res) { // Listen for the incomign request to a random room
io.emit(`message_${req.params.roomId}`, { message: 'A user has joined your room!' }); // Emits to the room that a user has joined
// Send the user some sort of HTML page
});
server.listen(3000, () => console.log('server is online');

然后在HTML文件中,监听消息

<!DOCTYPE html>
<html lang="en">
<body>
<!-- Some HTML script -->
</body>
<script src="/socket.io/socket.io.js"></script> <!-- Import socket.io -->
<script>
let socket = io.connect(); // Connect to the server
let room_id = (window.location.href).split('/')[(window.location.href).split('/').length - 1]; // Get the last param in the URL
socket.on(`message_${room_id}`, function(data) { // Listen for the message specific to the room
// Do something with the data
});
</script>

最新更新