Soket IO:发送到特定套接字连接而不是所有连接

时间:2018-03-01 19:38:31

标签: angular socket.io

在我的角度应用程序中,我有Kafka消费者向UI发送所有消息,并且其制作UI非常重,以过滤这些消息。

因此,当我通过角度应用程序连接时,我通过套接字IO连接传递参数中的过滤器。我在消费者方面也接收到该参数,但问题是当第二个连接请求来自具有参数的其他用户时,它会考虑该参数而不是第一个参数。

以下是我的代码

Angular 4服务方法 [客户端]

getFeed(Ids: any) {
    const observable = new Observable(observer => {

    this.socket = io.connect('http://loclahost:3007', { query: 'Ids=' + Ids + '' });

    this.socket.on('message', (data) => {
        observer.next(data);
      });
    });
    return observable;
}

Kafka Consumer Code [Server.js]

'use strict';
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
var Kafka = require('no-kafka');
var bodyParser = require('body-parser');
let techIds = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

app.get('/', function (req, res) {
    res.send("hello.");
});

//Socket IO Method
io.on('connection', (socket) => {
  console.log('USER CONNECTED');
  this.techIds = socket.handshake.query['Ids'];
  console.log(this.techIds);

  socket.on('disconnect', function(){
   console.log('USER DISCONNECTED');
  });

});

http.listen(3007, () => {
  console.log('started on port 3007');
  var consumer = new Kafka.SimpleConsumer({
        connectionString: 'localhost:29092,localhost:29093,localhost:29094',
        clientId: 'no-kafka-client'
    });

    var dataHandler = function (messageSet, topic, partition) {
        messageSet.forEach((m) => {
            console.log(topic, partition, m.offset, m.message.value.toString('utf8'));
            if(topic=="MyMessage")
            {
                const msg = JSON.parse(m.message.value.toString('utf8'));
                if(this.techIds != null && this.techIds != undefined && this.techIds.indexOf(msg.techID.toLowerCase()) > -1)
                    io.emit('message', JSON.parse(m.message.value.toString('utf8')));
            }
        });
    }.bind(this);

    return consumer.init().then(function () {
        var v1= consumer.subscribe('JourneyDetails', [0, 1], dataHandler);
        var arr=[];
        arr.push([v1]);
        return arr;

    });
});

例如,

第一个用户的套接字连接请求是http://localhost:3007?Ids=pm1,pm2,pm3

第二个用户的套接字连接请求是 http://localhost:3007?Ids=pm8,pm9,pm10

因此,在第二行请求中,参数值会被覆盖。

if(this.techIds != null && this.techIds != undefined && this.techIds.indexOf(msg.techID.toLowerCase()) > -1)
                    io.emit('message', JSON.parse(m.message.value.toString('utf8')));

这里我得到this.techIds值“pm8,pm9,pm10”所以在第一个请求中我得到的信息是pm8,pm9,pm10而不是pm1,pm2,p3。

任何建议或帮助都将不胜感激。

谢谢, 普什卡

2 个答案:

答案 0 :(得分:1)

我对作为解决方案的一部分所做的事情并不满意,但现在正在运行。

不开心,因为我遇到了客户端阵列的内存问题。当超过1000个用户连接时,它变得如此沉重。我的for循环花了太多时间来过滤记录。

随意提供您的建议/输入以优化以下代码。

import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("Downloads/sample1.wav")
wave_obj2 = sa.WaveObject.from_wave_file("Downloads/sample2.wav")
wave_obj.play()
wave_obj2.play()

答案 1 :(得分:0)

我认为你应该阅读这篇文章:https://socket.io/docs/emit-cheatsheet/#

    io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

};