首页 > 解决方案 > 广播数据

使用 socket.io

问题描述

我正在尝试为我的大学做一个项目,这是计划:

当客户端单击按钮时,必须将特定文本发送到服务器,然后将其广播到特定区域(部分或 div)。

有一些额外的功能(聊天和视频通话)让我理解代码有点令人沮丧。

这是我的 HTML 部分代码

<button type="submit" onClick = "btn1Clicked()">Data</button>
        <section id="data">

        </section>
<script>
function btn1Clicked(){
        socket.emit('data', function(data){
            socket.send("data");
        });

}
</script>

服务器js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
var ent = require('ent');
// Loading the page index.html
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket, username) {
    // When the username is received it’s stored as a session variable and informs the other people
    socket.on('new_client', function(username) {
        username = ent.encode(username);
        socket.username = username;
        socket.broadcast.emit('new_client', username);
    });
    // When a message is received, the client’s username is retrieved and sent to the other people
    socket.on('message', function(message) {
        message = ent.encode(message);
        socket.broadcast.emit('message', {
            username: socket.username,
            message: message
        });
    });
    socket.on('video call', function(data) {
        socket.broadcast.emit('video call', data);
    });
    socket.on('data', function() {
        console.log('data');
    });
});
server.listen(8080);

我需要向服务器 js 和 html 添加什么才能将其广播回 html 并将其添加到 div?

提前致谢。

标签: node.jssocket.io-1.0

解决方案


推荐阅读