不能为所有连接的客户端更改标签的内容



我的问题是: 与套接字。我向服务器发送请求,并从服务器向客户端发送请求,以便当客户端接收到此请求时,它修改测试中所有客户端的p标记内的文本,除非它不起作用,它仅为我修改它,而不是为所有连接的客户。

下面是我的代码:

client.js用于前端:

let buttonStart = document.getElementById('startButton');
let text = document.getElementById('text');

buttonStart.addEventListener('click', () => {
socket.emit('send');
console.log('send to server');
})
socket.on('send', () => {
text.innerHTML = 'test';
console.log('receive on client')
})

app.js后端:

const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const path = require('path');
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });
const publicDirectory = path.join(__dirname, 'public');
app.use(express.static(publicDirectory));

app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
})
httpServer.listen(3000);
console.log('Serveur en ligne...');

io.on("connection", (socket) => {
socket.on('send', () => {
socket.emit('send');
console.log('send to client from server');
})
});

我不能为我所有打开的窗口,我的客户端改变这个html标签的内容。

如果我正确理解您的问题,您应该以这种方式更改您的服务器端代码

io.on("connection", (socket) => {
socket.on('send', () => {
socket.broadcast.emit('send'); //this send the message back to all the clients except the one that send the original message
console.log('send to client from server');
})
});

io.on("connection", (socket) => {
socket.on('send', () => {
io.of('/').emit('send'); //this send the message to all connected clients
console.log('send to client from server');
})
});

最新更新