【问题标题】:How to implement private chat in php using nodejs and socket.io如何使用nodejs和socket.io在php中实现私聊
【发布时间】:2015-06-16 08:53:15
【问题描述】:

我已经使用这个实现了聊天应用程序(https://github.com/jdutheil/nodePHP),but 现在我想要两个用户之间的私人聊天,但我不知道如何实现它。请帮我解决以下问题。

当用户登录他的帐户时,它会列出(使用带有朋友姓名的超链接)他的朋友,例如 Facebook,并带有与之关联的唯一 ID,单击每个项目时,它会打开带有文本框和按钮的新聊天页面并开始聊天。这里是代码

开始聊天-with-friends.php

<?php
  //uniqueid of the friend
  $id=$_GET['id'];
?>
<form class="form-inline" id="messageForm">
                <input id="messageInput" type="text" class="input-xxlarge" placeHolder="Message" />
                <input type="submit" class="btn btn-primary" value="Send" />
            </form>

chatclient.js

$( "#messageForm" ).submit( function() {
var msg = $( "#messageInput" ).val();
socket.emit('join', {message:msg} );
    $( "#messageInput" ).val('');
});



chatServer.js**

socket.on('join', function( data ) {

io.sockets.emit('new_msg'+data.to,{message:data.message});
    });

【问题讨论】:

    标签: javascript php node.js


    【解决方案1】:

    你好,这可能对你有帮助

    var users = {};
    var sockets = {};
    
    io.sockets.on('connection', function(socket) {
    
    // Register your client with the server, providing your username
    socket.on('init', function(username) {
        users[username] = socket.id;    // Store a reference to your socket ID
        sockets[socket.id] = { username : username, socket : socket };  // Store a reference to your socket
    });
    
    // Private message is sent from client with username of person you want to 'private message'
    socket.on('private message', function(to, message) {
        // Lookup the socket of the user you want to private message, and send them your message
        sockets[users[to]].emit(
            'message', 
            { 
                message : message, 
                from : sockets[socket.id].username 
            }
        );
    });
    });
    

    【讨论】:

    • 我已经实现了,但是需要两个用户私聊
    猜你喜欢
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2013-02-06
    • 1970-01-01
    • 2012-01-29
    • 2016-04-12
    • 2016-09-11
    相关资源
    最近更新 更多