Function for receive notifcation alert in websocket php?

Viewed 57

I am working in Php with websockets for "one to one chat" module,I am new in "websockets", Here is my code

<script>
    var conn = new WebSocket('ws://localhost:8282');
    
    var client = {
        user_id: <?php echo $user_id; ?>,
        recipient_id: null,
        type: 'socket',
        token: null,
        message: null
    };

    conn.onopen = function (e) {
        conn.send(JSON.stringify(client));
        $('#messages').append('<font color="green">Successfully connected as user ' + client.user_id + '</font><br>');
    };

    conn.onmessage = function (e) {
        var data = JSON.parse(e.data);
        if (data.message) {
            $('#messages').append(data.user_id + ' : ' + data.message + '<br>');
        }
        if (data.type === 'token') {
            $('#token').html('JWT Token : ' + data.token);
        }
    };

    $('#submit').click(function () {
        
        client.message = $('#text').val();
        
        $('#messages').append(client.message + '<br>');
        
        client.token = $('#token').text().split(': ')[1];
        client.type = 'chat';
        if ($('#recipient_id').val()) {
            client.recipient_id = $('#recipient_id').val();
        }
        conn.send(JSON.stringify(client));
    });
</script>

I want to know that

  1. can we set "Userid" from our side ? or this "Userid" is issued by server ?
  2. we are using "conn.onmessage" for receive message but which function should be use for receive "notifcation" (when specific notification come for specific user) ?
0 Answers
Related