node.js - 阻止客户端发送消息socket.io

标签 node.js sockets socket.io

我想知道如何防止连接的客户端侵入代码并发送消息。

nodejs服务器代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http ,{serveClient: false});
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
    serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});


io.on('connection', function(socket){


    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            io.emit('chat message', body);
        }
    });


});


http.listen(port, function(){
    console.log('listening on *:' + port);
});

我使用 webSocket 来让用户了解最新的货币价格。 我想阻止用户向其他客户端发送数据。

最佳答案

客户端与客户端交互中涉及的步骤。 为简单起见,我使用自定义套接字事件名称作为“聊天”

  1. 客户端发出“聊天”事件
  2. 服务器监听“聊天”事件并获取消息
  3. 服务器然后发出“聊天”事件来发送消息
  4. 相应的客户端监听“聊天”并接收消息

每条消息都会经过您的服务器。因此您可以限制任何客户端与客户端的交互。

<小时/>

此外,每次新客户端连接时,socket.io(写在问题中)都会向所有连接的客户端发送货币价格。相反,当客户端通过 GET 请求连接时发送价格。然后在价格更新时发送更新的价格。

将套接字代码替换为遵循上述模式的新代码

关于node.js - 阻止客户端发送消息socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46973227/

相关文章:

javascript - Node 的子进程 "much"是否更慢?

ios - 让 GCDAsyncSocket 快速获取 SSL

c - 在 C 中用 select() 读取然后写入?

node.js - socketio中 `socket.broadcast.to(param)`的用途是什么

socket.io - 如何使用socket.io连接两个应用程序

node.js - 快速路线无法运行

javascript - nodejs hapiJs : Sending, 从客户端接收数据

java - 如何在Java中忽略数据类型读取数据流

javascript - Express - 将 mysql 连接传递给脚本

python - 波涛汹涌的在线 python 游戏