PHP REDIS NODE.JS多个发布者/订阅者

I want to create a privatechat.

Explanation:

Imagine you are User_1 you open a list of users[User_2, User_3 ...etc], every element has a button after clicking on one specific button I want to start a chatwindow with the specific user. (Server-side Laravel Project port: 8000) to use Websockets effectivly I'm running a node.js server, too(port 3000). To transmit data from php to node.js I'm using redis Pub/Sub, ChatController.php:

class ChatController extends Controller
{

   public function toChat($ForeignUserId)
   {
    $fid = (int) $ForeignUserId;
    $uid = (int) Sentinel::getUser()->id;

    $CollectionName1 = $fid . "collection" . $uid;
    $CollectionName2 = $uid . "collection" . $fid;
    $roomName = $uid . "room" . $fid;

    $res = DB::table('chats')
              ->where('collection_name', '=', $CollectionName1)
              ->orWhere('collection_name', '=', $CollectionName2)
              ->take(1)
              ->get();

    if(count($res) == 1)
    {
      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $res[0]->room_name, 'collection' => $res[0]->collection_name]));
    }
    else
    {
      $date = date('Y-m-d H:m:s');
      DB::table('chats')->insert(['collection_name' => $CollectionName2, 'room_name' => $roomName, 'sender' => $uid, 'receiver' => $fid, 'created_at' => $date]);

      //$client = new MongoDB\Client;
      $client = new Mongo;
      $companydb = $client->chat;
      $result1 = $companydb->createCollection($CollectionName2);

      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $roomName, 'collection' => $CollectionName2]));
    }
    //return view('chat');
    $url = "http://localhost:3000";
    return Redirect::to($url);
   }
}

Node.js File (server.js port:3000) receiving data:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoClientInstance = require('mongodb').MongoClient;
var redis = require('redis');
var php_listener = redis.createClient();

   app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
   });


php_listener.subscribe('chat-channel');

php_listener.on('message', function(channel, message){
   var purchase_data = JSON.parse(message);
   let colName = purchase_data.collection;
   let roomName = purchase_data.IOroom;

   let data = [];
   data.push(purchase_data.idone);
   data.push(purchase_data.idtwo);
   data.push(purchase_data.collection);
   data.push(purchase_data.IOroom);

   http.listen(process.env.PORT || 3000);
   console.log('Server running...');

   io.on('connection', function(socket){
       socket.join(roomName);
       io.sockets.in(roomName).emit('roomChat', data);
   });
});

My problem is following: I'm User_1 clicking on button2 (so open Chat with User_2, get all information: websocket_room (I'm calling it IOroom), mongodb_collection etc...)

Now lets pretend I'm User_3 (using other browser) and clicking on button 4 (to chat with user_4) I'm joining the websocket_room and still getting all information from User_1 (from which button he clicked)(websocket_room, mongodbcollection, etc...) Console.log result as User_3:

 (4) [2, 1, "2collection1", "2room1"] 
 (4) [4, 3, "4collection3", "4room3"]

What I'm missing? What do I have forgotten?

2个回答



您的Node.js应用程序有一个奇怪的代码。 我认为您不了解代码的每一行。 例如:</ p>

  //此代码将在Redis 
app.get('/',function(req,res){
res中的每条消息上添加快速路由规则 .sendFile(__ dirname +'/ index.html');
});

nn

在您实施聊天之前,您应该做出以下决定:</ p>


  1. 前端如何发送新消息? 通过带有Laravel的REST API或带有Node.js的WebSocket?</ li>
  2. 在升级连接到WS期间,前端如何进行身份验证? Node.js会向Laravel发出请求或Node.js会向数据库发出请求吗?</ li>
  3. 您是否应该将聊天对话存储到任何存储文件系统或数据库?</ li>
  4. 你会路由到你的Node.js和Laravel应用程序Nginx或任何类似Nginx的东西吗?</ li>
    </ ol>
    </ div>

展开原文

原文

You have a strange code for your Node.js application. I think you don't understand every line of your code. For example:

//this code will add express routeing rule on every message in Redis
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

Before you will implement your chat, you should make decisions about:

  1. How will front-end send a new message? Through REST API with Laravel or WebSocket with Node.js?
  2. How will front-end authenticate during upgrade connection to WS? Node.js will make a request to Laravel or Node.js will make a request to a database?
  3. Should you store chat conversation to any storage filesystem or database?
  4. Will you Nginx or any Nginx-like thing for routeing to your Node.js and Laravel applications?

dpg2905
dpg2905 我没有发布所有代码,因为我认为问题是在redis的多个订阅者/发布者中,或者我错了吗? 是的,Express的路由现在在redis订户功能之外。 :)
大约 3 年之前 回复
douji7399
douji7399 嗨@galkin,聊天应用程序被设计为来自laravel-project的外部应用程序1.带有Node.js的WS前端index.html:socket.emit('new message,{data ...})2。 Node.js正在使用Mongodb:mongo.connect('mongodb://127.0.0.1/chat',function(err,db){var col = db.collection(colName);在socker.on中('新消息) ',... col.insert({name:name,message:message},function(){data ....}})3。回答2.?4。我正在使用我的localhost apache,但是 我正在阅读如何使用Nginx :)我很感激你的想法。:)我还没有发布所有的代码。
大约 3 年之前 回复



理论 - 解决方案:
AMQP-Server,并在node.js服务器上添加会话。 现在我知道如何设置聊天服务器。 我自己想出来了...... </ p>
</ div>

展开原文

原文

Theoretical-Solution: AMQP-Server, and add session's on the node.js server. Now I know how to setup a Chat-Server. I figured it out by myself...

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问