【问题标题】:Pubnub One to One Chat Sending Message to all usersPubnub 一对一聊天向所有用户发送消息
【发布时间】:2018-05-07 10:07:52
【问题描述】:

这是我的 Pubnub 聊天代码

 var pubnub = PUBNUB.init({
    publish_key   : 'my_key',
    subscribe_key : 'sub-key'
});

  pubnub.subscribe({

    channel : "{{$channel}}",

    message : function(m){

     $(".conversation-list").append(
        '<li class="clearfix '+ m.clearifix +' ">' +
        '<div class="chat-avatar">' +
        '<img src="' + m.image + '">'+
        '<i> {{date('h:i')}}  </i>' +
        '</div>' +
        '<div class="conversation-text">' +
        '<div class="ctext-wrap">' +
        '<i> '+ m.name + '</i>' +
        '<p>' + m.message + '</p>' +
        '</div>' +
        '</div>' +
        '</li>'
        ).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
     $('.reply-text').val('');

 },
     //connect : publish
 });

  $('.send-reply-to-user').on('click', function (e) {
    e.preventDefault();

    if ($('.reply-text').val()== '')
        return false;
    else

        console.log(pubnub.publish);
   // console.log(this);

    var user_to_id = $(".send-reply-to-user").attr('user_to_id');
    var message = $('.reply-text').val();
    var name = $('#user_name').val();
    var image = document.getElementById("user_image").getAttribute("src");
    var clearifix = $('#user_clearifx').val();

    pubnub.publish({
        channel : "{{$channel}}",
        message: { name : name, message : message, image : image, clearifix : clearifix }
    });

    if ($.trim(message).length != 0) {
        $.ajax({
            url: '{{route('send:user:chat:message')}}',
            cache: false,
            method: 'POST',
            data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
            beforeSend: function () {
            },
            success: function (result) {
            }

        })
    }

});

此代码运行良好,唯一的问题是消息会发送给所有用户,我想将消息发送给一对一的用户。

Example: User one: John send a message to User two Deo, 
Example 2: John sends a message to Marry

等等。使用 Pubnub JS API,后端为 Laravel 5.6

【问题讨论】:

    标签: javascript laravel-5 chat real-time pubnub


    【解决方案1】:

    我建议使用名为 ChatEngine 的 PubNub 固执己见的 JavaScript 框架。它消除了与 PubNub 聊天所涉及的大量繁重工作。下面是一些示例代码,可帮助您开始进行 1:1 私人聊天。确保您使用setup button 为您的帐户准备后端。

    <script src="https://cdn.jsdelivr.net/npm/chat-engine@0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
    // Init ChatEngine with PubNub
    const publishKey = '__Your_PubNub_Publish_Key__';
    const subscribeKey = '__Your_PubNub_Subscribe_Key__';
    
    const ChatEngine = ChatEngineCore.create({
      publishKey,
      subscribeKey,
    }, {
      globalChannel: 'global',
    });
    
    const user = {
        uuid: 'randomstringofchars',
        name: 'John Smith'
    }
    
    const chats = {};
    
    ChatEngine.connect(user.uuid, user);
    
    ChatEngine.on('$.ready', function(data) {
    
        // store my new user as `me`
        let me = data.me;
    
        // returns a ChatEngine chat object
        function makePrivateChat(theirUserId) {
            const chatKey = [theirUserId, me.uuid].sort().join('-');
    
            // Don't make the same 1:1 chat if it already exists
            if (chats[chatKey]) {
                return;
            }
    
            // true for private chat
            const chat = new ChatEngine.Chat(chatKey, true);
    
            chats[chatKey] = chat;
        }
    
        // Auto add a 1:1 chat to UI when invited by someone
        me.direct.on('$.invite', makePrivateChat);
    
        // Define a button for making new 1:1 chats in your UI
        newOneToOneChatButton.on('click', function (event, theirUserId) {
            someChatObject.invite(theirUserId);
        });
    });
    </script>
    

    【讨论】:

    • 这意味着所有用户都存储在一个单独的全局频道中,ID分开,当我检索聊天时如何找到单个用户的聊天??
    • 所有加入应用的用户都连接到全局聊天。它们都有不同的uuids,您可以定义它们。您可以像我的回答一样进行自己的私人聊天。每个聊天对象都存储在ChatEngine.chats
    【解决方案2】:

    终于解决了我的问题,私人频道运行良好,实际上问题出在我的后端。它正在从我修复的所有用户那里返回数据,现在它工作正常。

    【讨论】:

    • 如果可以的话,能否分享一下源代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多