Jump to content

Live chat


jaymc

Recommended Posts

I want to make an ajax live chat system for my website

 

That I can do, however, in order to run live when a member request to chat with another member, a row is inserted into the database pointing to there member id

 

They then get notified that someone wants to chat and hey preston the chat has started

 

My problem and question is, in order for this to work live, obviously im going to have to secretly query that table every minute for instance to check for chat requests

 

So, for every member online, thats 1 query a minute to check for a chat link in the database

 

What if.. there was 600 people online?

 

The table would nearly always only contain 10 rows at max as I will have them delete when the chat starts.. so that will be fine but 600 queries per minute just for this live chat system

 

Is there a better way, I cant wait for them to do a page refresh, has to run live in the background and update asap when someone wants to chat

 

Any ideas..

Link to comment
Share on other sites

Dam, I didnt want to hear the inevertable

 

How do websites with 5000 users online go about it?

 

For instance, faceparty, they have 18,000 members online at any one time usually

 

18,000 queries every 30 seconds just for a chat system is unthinkable, right?

Link to comment
Share on other sites

I've always wondered how the hell some places do it, kinda like an AIM system really. Sure, I've got this coding down for getting messages, but I've got speed issues. I assume that the only way to fix this is to have like 500 servers dedicated only to chatting (you've gotta be rich :-o)

Link to comment
Share on other sites

Well AIM system uses different protocols that allow for two way communications... it's different for websites. Also big websites have bigger badder servers and more of them. Also... while the connection takes some time, generally speaking the time isn't in executing the queries, it's in doing the presentation. So if you're pulling back a boolean (were there results or not) it's going to be fairly efficient.

Link to comment
Share on other sites

while the connection takes some time, generally speaking the time isn't in executing the queries, it's in doing the presentation. So if you're pulling back a boolean (were there results or not) it's going to be fairly efficient.

 

Pulling back a boolean?

 

The chat would use a refresh aswell once initiated, perhaps a refresh every 5 seconds for both clients although not a serious issue as not everyone on the website will be chatting at the same time

 

Pulling back a boolean though.. can you explain?

Link to comment
Share on other sites

Please don't use flat files.

 

Overtime as the things grow, processing becomes less and less efficient... you have to custom write interfaces to use them... you have to custom write any reports against them.

 

Please use a database for all sorts of reasons.

Link to comment
Share on other sites

Again, that kinda sounds like a lotta coding. For one thing, checking to see if the chat is over would be if no new comments/messages over a certain time period. Then inserting into the database, I do have to admit this sounds like a fun idea.. But what if they don't close the window and continue the chat, they may encounter an error... Sounds a bit too much o_o

Link to comment
Share on other sites

you could also check for inactivity... I have a function for that:

http://phpsnips.com/snippet.php?id=39

 

This function would need to be modified some, because it currently logs people out, so it would need to be changed to save a file file after in activity (I think this is what you meant in the last sentence).

 

By the way, you can use php for xml: http://us.php.net/xml

Link to comment
Share on other sites

Some good feedback

 

I think using a few flat files may be a good idea, but definately will be database driven

 

Just to clarify, regardless, I am going to have to run concurrent queries continuously every 3 seconds to check for new messages

 

There is no way around this. Silly question but I was thinking of how a telephone works

 

Your telephone doesnt check every phone line in the world for an incoming call, it rings when the other person contacts it

 

Is there a way for my server to talk to the client who is doing nothing but 'listening' rather than 'checking'

 

I think this would involve an applet perhaps, but, any ideas would be great

 

Essentually, if someone can just confirm I must have concurrent checks for new messages..

Link to comment
Share on other sites

Let's talk switch boards LOL

 

Telephone A

Telephone B

 

If A calls B, it routes through wires. B is almost always checking to see if there is a call coming through. The signal hits the phone, the phone keeps recalling to check if there are any new calls. A will pick up the signal in one of it's "re-checks", makes contact, and keeps re-looping to keep in contact.

 

I do wish there was some "listening" thing, but I do believe that in the world of PHP, it's almost non-existent.

Link to comment
Share on other sites

It's really a pretty simple concept with Ajax.

 

You have a table that you store chat "transactions" this has a PK of some auto number ID. You query the database for chat information between these users where the ID is greater than whatever stored ID you have. Then you update the stored ID with the last ID. After X seconds your Ajax call requeries the database with the new stored ID so that only new records are pulled back.

 

If you don't like this route... you do the same thing with an auto refresh via the meta stuff or javascript.

 

But no, you're not going to get a "listening" functionality native in PHP. PHP runs on the server and cannot force the browser to request more information... that's what the Javascript part of Ajax does for you.

 

I actually wrote a basic chat thing back in the day using the approach I described above. The idea had never occured to me to do it this way... and came to me one day sitting in a class. I sat down and was able to whip up a working version within 45 minutes.

Link to comment
Share on other sites

I wrote this myself and it works like a charm for me, I can see some ppl are struggling so I'll share..... I stripped it down to its simplest form to make it easy and adaptable to you gents...

 

My SQL table:

CREATE TABLE `logs_chat` (
  `uName` varchar(128) NOT NULL,
  `mTime` int(10) unsigned NOT NULL default '0',
  `mBody` varchar(128) NOT NULL,
  KEY `mTime` (`mTime`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

My Javascript

function keyup(arg1) { 
if (arg1 == 13) submit_msg(); 
}

^-- Checks the keys hit to see if they hit enter and if they did submit the message

 

function GetXmlHttpObject() {
var xmlhttp = null;

if(window.XMLHttpRequest){
	xmlhttp = new XMLHttpRequest();
	if(xmlhttp.overrideMimeType){
		xmlhttp.overrideMimeType('text/xml');
	}
} else if(window.ActiveXObject){
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e){
		}
	}
}

if(!xmlhttp) {
	alert('Giving up  Cannot create an XMLHTTP instance');
	return false;
}

return xmlhttp;
}

^-- used to create constant polling

 

function ajax_read_window() {
xmlhttp1 = GetXmlHttpObject();
xmlhttp1.onreadystatechange = function() {
	if (xmlhttp1.readyState==4 || xmlhttp1.readyState==0) {
		document.getElementById("chatwindow").innerHTML = xmlhttp1.responseText;
		var init1 = setTimeout("ajax_read_window()", 500);
	}
}
xmlhttp1.open('GET','/includes/inc-chat.php?type=r',true);
xmlhttp1.send(null);
}

^-- Checks the chat window to get the messages

 

function submit_msg() {
xmlhttp3 = GetXmlHttpObject();
msg = document.getElementById("message").value;
document.getElementById("message").value = "";
xmlhttp3.open('GET',"/includes/inc-chat.php?message="+msg+"");
xmlhttp3.send(null);
ajax_read_window();
}

 

And in chat.php (the chat page users see)

<div id="chatwindow" style="width: 445px; height: 394px; padding-top: 45px;"><noscript><span style="color: #FFFF00; font-weight: bold">You must have javascript enabled in order to view this chat room.</span></noscript></div>

<input type="text" autocomplete="off" id="message" onkeyup="keyup(event.keyCode);" style="width:450px; height:40px" maxlength="144">

<script type="text/javascript">
ajax_read_window()
ajax_read_online()
</script>

 

 

And in /includes/inc-chat.php

// YOUR USER INFO stuff goes here, etc, whatever you use in PHP to distinguish your users as your users and make sure they are logged in

if ($_GET['message']) {
$_GET['message'] = trim(mb_strcut($_GET['message'], 0, 144));

if ($_GET['message']) {
	$message = str_split($_GET['message'], 48);
	mysql_query('INSERT INTO `logs_chat` VALUES ("'.$user['uName'].'", '.$channel.', '.$_SERVER['REQUEST_TIME'].', "'.$value.'")');
}
} else if ($_GET['type'] == 'r') {
$total = mysql_result(mysql_query('SELECT count(0) FROM `logs_chat` WHERE `mTime` > '.($_SERVER['REQUEST_TIME'] - 600)), 0);
$start = (($total - 24) > 0) ? ($total - 24) : 0;
$query = mysql_query('SELECT * FROM `logs_chat` WHERE `mTime` > '.($_SERVER['REQUEST_TIME'] - 600).' ORDER BY `mTime` ASC LIMIT '.$start.', 24');
while ($message = mysql_fetch_assoc($query)) {
	echo '<span style="color: #FF9900; font-weight: bold">'.$message['uName'].$extra.'</span> <em>@ '.date('H:i', $message['mTime']).'</em>: '.$message['mBody'].'<br>'; }
}
}

Link to comment
Share on other sites

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.