-3

I want to write a chat application, using jQuery and PHP. The part that I need help on is where a real time user "Evx" is typing a message and then show that message to all other users in real time. This would be similar to how Skype has a pen ../ and how Facebook has a notice when the user types.

What I need is some assistance with the logic steps and information on how to easily accomplish the real time "user is typing" but still have it work as well as any other way.

Here is what I've tried so far:

//time delay before ajax call
var delay = (function() {
    var timer = 0;
    return function(callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

$('#usermsg').keydown(function() {
    if ($('#usermsg').val().length === 5) {
        delay(function() {
            $.ajax({
                url: "addusertyping.php",
                cache: false,
                success: function() {

                }
            });
        }, 5000);
    }
});

$('#usermsg').keyup(function() {
    if ($('#usermsg').val().length >= 6) {
        // here I should basically check for 
          // an update from server or what not.
    }
});​

Can someone please explain the steps and information on how to achieve user typing real time, using what I've tried above as a starting point?

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
EVX
  • 304
  • 4
  • 17
  • 8
    You should ask a concrete programming question. your question is overly broad I'm afraid. – gdoron May 13 '12 at 01:12
  • 1
    I would argue that the above question is perfectly fine, the guy seem to have a glance of what he was trying to do and you guys here shuttered his/her dreams! Look at the answer below, couldn't everyone else give the right direction as @jmort253 did in the lonely answer below? Remember, even new programmers land on Stackoverflow and people's exceptional skills chase them away! – Morgs Dec 31 '15 at 07:59

1 Answers1

13

The approach that sites like Facebook and Google Talk use when implementing chat is to use solutions that capitalize on the request/response model of the Web using Comet or Reverse AJAX.

Web 1.0:

In traditional Web 1.0 implementations, such as yours, the browser initiates a request to the server. The server responds with data that the client side code renders in the view.

This works great when we're simply moving users from one page to another or when we're responding to events that are initiated by the user. However, this methodology is inherently flawed when it comes to managing events that are initiated by the server.

In your example, in order to simulate real time updates, you must hammer the server with continuous polling requests to check for updates. This is the equivalent of the little kid in the back seat of the car that constantly and incessantly asks his parent "Are we there yet? Are we there yet?" over and over again without fail. This not only eats up a lot of bandwidth but creates heavy load on the server when the number of connected clients scale up.

Comet/Reverse AJAX:

Since the server cannot initiate responses to the browser without a request, a technique called "reverse AJAX" or "Comet" is used to simulate the process of the server pushing event notifications to the client.

The general premise behind Comet is that the browser opens a connection to the server and then the server holds that connection open indefinitely. When the server then has an update that it needs to pass to all connected clients, it then sends the response back to the client, completing the request/response cycle. Upon receiving the response, the clients immediately send another request to the server, which the server once again keeps open until the next update.

There are Comet solutions available for PHP, so this is something you could accomplish using your existing platform; however, I cannot recommend any. You'll also need a client-side library to facilitate opening the Comet connections. Check out the Dojo Cometd JavaScript Library.

Comet is one of two superior solutions for implementing a chat solution, with the other being WebSockets. However, support for WebSockets is still lacking in some browsers.

When looking for a library that facilitates Comet, it's also a good idea to select one that facilitates Continuations, which help to ensure that threads that are waiting to send a response can be released to perform other tasks instead of waiting idly by. With such a solution, some Comet servers have easily scaled to over 20,000 connections!

Here is an article that describes How to Implement Comet on PHP. Additionally, you may find this StackOverflow question useful as it describes the challenges of using Comet on PHP.

Design Considerations:

One of the first mistakes we made when developing our chat solution was in not thinking about messages as being a subclass of something more abstract. Instead, information we sent from the server to the frontend was simply a "Chat message". However, as the product advanced, we soon discovered that the same Comet connection could be used to send commands to the browser, not just messages.

Hence, to implement your "User is typing", you might need a handler in your JavaScript that first determines if the update from the server is a new message, or is it the "Show that user XYX is typing" command. A good design can also ensure that you can use the Comet connection for other types of updates as well that would initiate from the server.

Lastly, your User typing message should have some sort of delay on it such that when a user is typing, his or her browser will only notify the server once every X seconds. If you bind your user typing to a keypress event that simply hammers the server with AJAX requests, then you are simply degrading your Comet connection back into polling.

On the recipient end, you'll most likely want to implement a timeout feature so that the User typing message automatically disappears if the user who is typing stops sending "user typing" requests to the server. Alternatively, that user's browser could send a "User not typing anymore" message if the browser sends a request when his or her textbox is empty, such as when the user backspaces over text entered.

Easy Solutions?:

Finally, I want to add that this will involve a learning curve, as you must think about the Web from the perspective of the server pushing data to the client instead. This will involve lots of research and dedication on your part, as well as trying out examples and getting a really strong understanding of how you should approach the design of your application. This is by far one of the best ways to master this technique, but it can also be intimidating. Just be sure to take your time with the examples, try them yourself, and if you get stuck you can always ask for help.

Community
  • 1
  • 1
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • 1
    Very helpful comment, no idea why others couldn't answer this question in the same style but chose to abruptly close it! Thanks again you've set me into the right direction. – Morgs Dec 31 '15 at 07:56