node.js - 广播数据使用 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?
提前致谢。
解决方案
推荐阅读
- git - 您如何正确切换具有非分阶段更改的开发设备?
- javascript - Javascript 无法从使用 this 调用的方法设置属性
- python - 找不到 YAML 模块
- stripe-payments - Stripe 只收取金额的 1% - 测试模式
- php - 在搜索栏中以法语格式化日期
- c++ - 计算表示为字符串的 2 个大数之间的模数
- swift - 如何通过 Swift 映射来自 Firestore 的文档中的嵌套数据?
- r - 在模型中使用具有数百个级别的因子
- php - 选择查询中的 Laravel 传递列表参数(列)
- python-3.x - How to return string composed of superscript inside of fraction for matplotlib legend label?