7

I'm trying to create a PHP chat, so I have server.php that starts the server on the terminal, which is listen to client connections:

<?php

function chat_leave( $sock, $chat_id = 0 )
{
    if( $chat_room_id[ $chat_id ] )
    {
        unset( $chat_room_id[ $chat_id ] ); 
        return true;
    }
    socket_close($sock);
    return false;
}

function client( $input )
{
    /*
    Simple php udp socket client
    */

    //Reduce errors
    error_reporting(~E_WARNING);

    $server = '127.0.0.1';
    $port = 9999;

    if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Couldn't create socket: [$errorcode] $errormsg \n");
    }

    //Communication loop
    while(1)
    {

        //Send the message to the server
        if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port))
        {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);

            die("Could not send data: [$errorcode] $errormsg \n");
        }

        //Now receive reply from server and print it
        if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE)
        {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);

            die("Could not receive data: [$errorcode] $errormsg \n");
        }

        return $reply;
    }
}
/*
 * chat_join
 * a new user joins the chat
 * @username: String
 * @password: String
 * 
 * add a new listener to the server
 * 
 */
function chat_join( $username = "", $password = "" )
{
    $users = array(
        "batman" => "batman123",
        "robin"  => "robin123",
        "joe"    => "joe123"
    );
    if( $users[$username] == $password )
    {
        return true;
    }

    return false;   
}
function main()
{
    $chat_room_id = array();

    $username = stripslashes( $_POST['username'] );
    $password = stripslashes( $_POST['password'] );
    $action   = stripslashes( $_POST['action'] );
    $port     = intval( $_POST['port'] );
    $domain   = stripslashes( $_POST['domain'] );
    $chat_id  = intval( $_POST['chat_room_id'] );

    if( strcmp( $action, "login" ) == 0 )
    {
        $status = chat_join( $username, $password );
        if( $status )
        {
            $chat_room_id[] = $chat_id;
            echo json_encode( $status );
        }
    }
    else if( strcmp( $action, "chat" ) == 0 )
    {
        $msg = stripslashes( $_POST['message'] );
        // take the message, send through the client
        $reply = client( $msg );
        echo json_encode( $reply );
    }
    else if( strcmp( $action, "logout") == 0 )
    {

    }
    else
    {
        echo json_encode( false );
    }
    return;
}

main();

?>

The function client() is the code I have from a client.php file, which when I execute on the terminal, is able to send and receive messages from the server.php. Now I would like to use my main.php file, so once the user is logged in he will send messages to the server, which will reply back the messages that user haven't seen. When I run server.php and client.php from two different terminals, I'm able to send and receive messages, however I would like to do that using main.php, transform that reply message into a JSON object and send back to the html page where it will get appended to a textarea box. My problem is: how can I get the reply that client.php received and send it back to the html page? When I execute it on the terminal, I have:

Enter a message to send : hello
Reply : hello

I use AJAX to send the user input in the chat, so I wanted to be able to take that message, and send it to the server, which I started on the terminal and take the reply back and forward to the webpage and append that to the text box area. How can I accomplish that? Should I start client.php as a service through main.php? Or should I use the client($input) function to send a message and then return what it sends, back? However, I wanted that client to be running until the use logs out, because other clients may connect to the chat. How can I accomplish that is kind of fuzzy for me. The code in client( $input ) is the same as in client.php.

j0k
  • 22,600
  • 28
  • 79
  • 90
cybertextron
  • 10,547
  • 28
  • 104
  • 208
  • http://stackoverflow.com/questions/2055020/php-chat-client – sdolgy Dec 26 '12 at 10:25
  • Also keep in mind that PHP is not designed to run longer than one request. Is can run longer (did a chat bot a while ago) but you have a high risk of leaking memory and crashing if you aren't very very carefull. Other languages might be more suitable for resident apps. – ToBe Apr 17 '13 at 11:35

4 Answers4

1

Sorry for off-topic, but if you can, it would be better to use XMPP ready solution like ejabberd server with http-bind module. Sure, there is some cons it such solution, but cons are greater. Just look in this solution, maybe it will solve your problem with low cost.

see related answer with brief desc on XMPP solution

Community
  • 1
  • 1
pinepain
  • 12,453
  • 3
  • 60
  • 65
1

I think I understand what's going on. Sounds like you might be missing a listener? Usually chat programs have client-side ajax that checks or "listens" for messages for a particular user at regular intervals.

For example, if someone left a message for user x in your database (or wherever you're storing messages), the you might have some javascript that calls a php script every second to see if there are any messages on the server for user x. If there are, you can echo the message or messages back and received them via your ajax callback function.

If you're familiar with jQuery, check out the $.get method: http://api.jquery.com/jQuery.get/

bluemoonballoon
  • 299
  • 1
  • 2
  • 8
1

As i understand your question, you want to send a message from the client to the server and as soon as this message gets to the server it will reply to all clients... i'm correct???

I do some chat like using nodejs and other javascripts tech... and must say a great option here is using web sockets. Realize that browser support is limited, but since you not specified what browsers need to run this i think a great way to go.

Check this related links:

How to Use Sockets in JavaScript\HTML?

http://socket.io/

A possible way of doing that only using php + js is make some function and put in a setInterval to make request to the server every 12 seconds. I made some kind of asp chat in 2005 that uses this approach. And i must say the web socket is much better.

I don't know if that answers your question... let me know!

Community
  • 1
  • 1
rdenadai
  • 433
  • 2
  • 10
  • 1
    Websocket support is actually universal in all current desktop browsers, and node.js has sufficient fallbacks so that it works on all browsers since IE5.5. – Niels Keurentjes Apr 12 '13 at 21:59
1

I developed something along these lines before using PHP and jQuery. The solution I went for was due to the restrictions on the server setup(out of my control). I used a PHP core script to create the whole layout of the page from message window to message submission box. Any user that came to the page was given a randomly generated user like user123234234 generated off a unix timestamp from the time they entered the chat page.

All messages submitted were stored in an XML file and a new XMl file was created daily. The user was kept in a message node like below with details of the user for every message using different node attributes.

The message window was refreshed every 5 seconds using jquery AJAX call to another PHP script that read in the XML that days XML file only from the time the user entered the chat page.

<messages>
    <message user="user123456" ip="127.0.0.1" session="{users session ID here}" time="{unix timestamp}"><![CDATA[User message here]]></message>
</messages>

There is a lot more logic behind it but I found it the easiest to develop and maintain, I hope it help point you in the right direction. And it works on all major browsers and from IE7+.

llanato
  • 2,508
  • 6
  • 37
  • 59