douqi3195 2017-06-24 14:34
浏览 79

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条回答

  • doude2635 2017-06-24 15:27
    关注

    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?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建