Jump to content

Recommended Posts

I have a running chat application in my website. It is implemented using websockets, php and is working fine. The problem is whenever i send a message to single user it broadcasts that message to all users currently connected to my website. It will be really helpful if someone can tell me how to get the unique id of each user when someone connects to our app. If i can get the userid of the current logged in chat user that would solve my problem but i am unable to retrieve that userid when the user connects (open state of websocket). I can get the userid when the connection is made but I need the userid before the connection happens. When the connecation occurs it assigns its own ids to the connected users in a serial manner(1,2,3..,n).

<?php
// prevent the server from timing out
set_time_limit(0);

// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';

// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

// check if message length is 0
if ($messageLength == 0) {
    $Server->wsClose($clientID);
    return;
}

//Send the message to everyone but the person who said it
foreach ( $Server->wsClients as $id => $client )
    if ( $id != $clientID )
        $Server->wsSend($id, "Visitor $clientID ($ip) said "$message"");
}

// when a client connects
function wsOnOpen($clientID)
{
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

$Server->log( "$ip ($clientID) has connected." );

//Send a join notice to everyone but the person who joined
foreach ( $Server->wsClients as $id => $client )
    if ( $id != $clientID )
        $Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}

// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

$Server->log( "$ip ($clientID) has disconnected." );

//Send a user left notice to everyone in the room
foreach ( $Server->wsClients as $id => $client )
    $Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}

// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('127.0.0.1', 9300);

?>
<!doctype html>
<html>
<head>
<meta charset='UTF-8' />
<style>
    input, textarea {border:1px solid #CCC;margin:0px;padding:0px}

    #body {max-width:800px;margin:auto}
    #log {width:100%;height:400px}
    #message {width:100%;line-height:20px}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="fancywebsocket.js"></script>
<script>
    var Server;

    function log( text ) {
        $log = $('#log');
        //Add text to log
        $log.append(($log.val()?"n":'')+text);
        //Autoscroll
        $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
    }

    function send( text ) {
        Server.send( 'message', text );
    }

    $(document).ready(function() {
        log('Connecting...');
        Server = new FancyWebSocket('ws://127.0.0.1:9300');

        $('#message').keypress(function(e) {
            if ( e.keyCode == 13 && this.value ) {
                log( 'You: ' + this.value );
                send( this.value );
                $(this).val('');
            }
        });

        //Let the user know we're connected
        Server.bind('open', function() {
            log( "Connected." );
        });

        //OH NOES! Disconnection occurred.
        Server.bind('close', function( data ) {
            log( "Disconnected." );
        });

        //Log any messages sent from server
        Server.bind('message', function( payload ) {
            log( payload );
        });

        Server.connect();
    });
</script>
</head>

<body>
<div id='body'>
    <textarea id='log' name='log' readonly='readonly'></textarea><br/>
    <input type='text' id='message' name='message' />
</div>
</body>

</html>
Link to comment
https://forums.phpfreaks.com/topic/283152-websockets-group-chat-to-specific-users/
Share on other sites

Two ideas that come to mind.

 

Start saving users with an autoincrement id,username,ip into a db, and call on that first. Some sort of login system used to determine guest or user, if is a user generate a guest_number incremented.

 

Create sessions storing ip and datetime, set a cache expire on them, grab their real ip and use as the unique id.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.