Is using websockets for a webchat possible using a webhost? - php

I'm an inexperienced PHP programmer and I am making a website using Codeigniter which runs on a server of a webhost. This website should, among other functionality, contain multiple chatrooms where medium-sized groups (+/- 25 people) could have real-time chat sessions. The number of chatrooms depends on the popularity of the site, so the chat functionality should be scalable and I want to be prepared to host hundreds or thousands of chatrooms.
I've found that one way to do this, is using short-polling with ajax, i.e. saving every message in the database and polling the database every second. I thought this approach would not scale well (as it seems very intensive for the database), so I thought it would be better to use a long-polling approach, e.g. websockets with node.js.
I'm not experienced with using sockets and as far as I've seen, node.js requires you to use your own server (e.g. localhost). Ideally, I want to integrate the functionality of node.js in my website so that every upcoming message is pushed to all the other chat-users, and that the messages are once in a while (e.g. every 10 minutes) sent to the database, so that chat history could later be reviewed.
This doesn't seem possible as node.js needs to independently run on your own server. What could I do to make my chat work with websockets, while using the server of the webhost? Is this possible? Should I use a different webserver instead of a webhost, or should I stick to short polling? Many thanks in advance.

Related

XHR long polling for chat application (instead sockets)?

I need to create a user-to-user real time chat system. I managed to create a simple AJAX/PHP/MySQL script for the chat, but one thing worries me in the PHP/MySQL part:
while(true) {
// ...SELECT * FROM messages ORDER BY date DESC LIMIT 1...
if($row['date'] > $_POST['last']) {
echo json_encode($row);
break;
}
sleep(1);
}
Doesn't that mean that it will SELECT the table every 1 second and wouldn't that overload the server?
I tried to use PHP sockets, but it was a nightmare. I had to buy SSL certificate, also, the server was crashing on tests with many users, so I decided to use the long pulling system for now. If I remember correctly, Facebook was using XHR long polling before switching to sockets (if they switched at all).
Well, your question is too generalized. While it mostly depends on the load your will receive and your server specifics, it's generally discouraged to use long polling.
There are certain assumptions made in your question, that are not totally true at all.
I had to buy SSL certificate, also
Did you? As far as I know there are free certificate issuers, such as letsencrypt. The problem here is maybe you are using shared hosting with FTP only access. Consider getting a VPS from some cloud provider, e.g. DigitalOcean. You will have full-access to the virtual environment there. And most of the cheapest VPSs are on the same price you can get a shared hosting.
Facebook was using XHR long polling before switching to sockets
Yes, they were and some times they fall back to them too. But, first of all - they have a lot of computing power. They can afford these things. And second, the facebook web chat is not the fastest app I have ever used :)
-
With indexed columns and a few records on a normal MySQL single instance, you will not notice any slow downs. When the data grows and so do the users (simultaneous connections), you will gradually find out that you need to optimize things and one day you will eventually go to the WebSocket's favor.
PHP at heart is not meant to be asynchronous. All the async things along with the whole event loop you will need to either do by yourself or compose several frameworks to come to the rescue.
I would generally suggest a complete proprietary WebSocket implementation with asynchronous runtime. You either take a look at Ratchet for PHP or use ws for Node.js.

Is it possible to build real-time application using PHP , Socket.io and javascript only?

Lately, I have been doing a lot of research (of course googling :P) on building real-time application (like chat application). So far I have come across Elephant.io, Socket.io and Ratchet. And some of the terms I stumbled upon were web-sockets, bi-directional communication etc..
I am building an auction site where it involves countdown timer. I am trying to achieve something like when one user bids, the timer gets updated in all the client's browser without page refresh (something like server broadcasting the change of event to all other connected users).
The problem is, I am building the application with PHP (Pyro-cms). The server, where it will be uploaded is Apache-based server and does not support node.js. One of the most common stuff I notice was most of the real-time applications were utilizing node.js.
Is it possible to build real-time application using PHP , Socket.io and javascript only? or may be with angular.js?
I really cannot use the server that support node.js so have to completely rely on apache server. I even dont know if it is possible. If there is any resources, reference or tutorial, it will be very helpful.

Does the Server-Sending PHP Script have to poll?

I have a web application driven primarily by javascript/ajax, somewhat similar to how google docs work; all people viewing a page will be seeing the same information in relative real-time. It's not crucial that the information is actually real-time, a second or so is fine.
Currently, the application is ajaxing the server every 5 seconds. I was researching server-sent events and they sound like exactly what I need... but this is my understanding: server-sent events essentially just move the polling to the server. The PHP script doing the server-sent events will check the database for changes every X seconds, and send an update to the application when it finds one.
Checking once per second would probably be adequate, but since I'm on shared hosting I want to avoid any unnecessary load possible. Is there way I can subscribe to updates to the database? Or is there a way I can notify the script from other PHP scripts that make changes to the database?
With PHP, polling the DB is the typical way to do this. You could also use TCP/IP sockets to connect to some kind of application server, that sits in front of your database, and knows about all writers and all consumers. I.e. when a write comes in, it both broadcasts it to all consumers and writes it to the DB. The consumers in that examples are the PHP scripts (one per SSE client).
If you use WebSockets, then you need exactly the same architecture, because PHP is single-threaded: each SSE connection is an independent PHP process.
If you switch to using, say, node.js, then that application server can be built-in. (Again, it would work the same way, whether SSE or WebSockets.)
But, you mention you intend to use shared hosting. SSE (and WebSockets, and comet technologies) hold a socket open, which interferes with the economics of shared hosting. So your sockets are likely to get closed regularly. My advice would be to stick with ajax (and therefore DB) polling every 5 seconds, instead of SSE, until your application is worth enough that the $10-$100/month for a real host is not an issue. Then consider using SSE to optimize the latency.
P.S. The decision between SSE and WebSockets is all about write frequency. My guideline is if your clients write data, on average, once a second or more frequently, web sockets are better, because it is keeping the write channel open. If once every 5+ seconds then web sockets does not bring much, compared to just using an Ajax post each time you have data to write. An SSE back-end is simpler to deal with than a WebSockets back-end. (Writes every 1-5 seconds is the grey area.)
What I would recommend is instead of polling the database for changes, you will know when there is going to be a database change because your application will be making that change. I would use web sockets (https://developer.mozilla.org/en-US/docs/WebSockets) and simply push an update to all active clients when any member makes a change.
Here is the difference between Server Send Events and Web Sockets. (In your case Web Sockets are the way to go)
Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.
Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.
SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.
In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.
However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.

PHP & COMET. Need some guidance

I have been in search of making live websites by using PHP. (COMET) I have been searching for a very long time already. (around a month) I have even checked some PHP chat scripts and used on my webserver, but I had some problems on most of them. (will be explained)
So far, most of the people tells the same thing: PHP isn't the best language could be used with COMET. The chat/comet examples are hacky at best.
I am asking this because, I want to have some features on my websites, like allow logged in people to chat with each other. That is where I need an alive connection to PHP pages. I am also planning on making a browser based game, and an alive connection will still be a must!
AJAX was a rare thing 2 years ago, shined with Facebook. Now pretty much everyone uses it, and it became a standard on web development. Now, the COMET based websites are growing. Youtube, Google+, Facebook, EA's Battlelog and such. I believe I should learn how to use it.
Okay, here are my questions. (Some of the information at below are the ones I gathered while searching on Google. Not sure if they're correct or not.)
Some languages like Python have special web servers designed for this job. I believe one of them is called Tornado Web Server. Developed and configured to simulate thousands of alive connections. I believe there is no such option in Appserv, but some people told NGINX can handle it with a decent configuration. Is it true? What configurations should be made? Is there any PHP web servers for this job?
Some of the most suggested things are:
a. Using APE.
b. Using Socket.IO
c. Node.js
Is there any way we can use them with PHP? Which one is the most promising? Could you give some guidance on them? Is there anything else than these?
I have used a comet chat script. Basically, you kept querying database and output the result with flush() to browser by sleeping it with usleep() in a loop. (This one became hard to understand so I will provide a quick code)
while(true)
{
// query database
// output the result
// flush the browser
// sleep for few seconds to lower cpu load
}
usleep() function basically destroyed my web server on Windows based operating systems. Is it normal to rely on usleep() on comet applications which runs on windows based OS? I mean, is there even a way to "sleep" PHP scripts? No matter what I do, CPU load goes to %100 on both WIN and UNIX servers.
Is PHP "really" that weak on this area? Should I give up with PHP and focus on other languages? If so, which language would you suggest? (That language should be promising. For example, there is no much use of AS3 after HTML5 addition, and AS3 is more likely to die soon while JS shines.)
What is WebSync? Can it be used with PHP?
Please bear in mind that I need to use COMET to make following applications:
A chat script, where logged in players will be able to chat eachother.
A browser based game. I already use JSON/AJAX and things like that when coding, but to receive opponents steps, I should pull the data, so an alive connection is needed. (Don't imagine advanced games, I am speaking about games like chess at best.)
I would appreciate if you can give me a short guidance. After all, I have been getting confused day by day since there are SO MANY random articles on internet. People even call setInterval() as COMET, so it is a complete mess.
There needs to be some clarification here. What you're looking for is not language specific per se. If you wanted to achieve the comet functionality with PHP you'd be relying on the Web Server (e.g Apache) to do the HTTP streaming. Also you need to understand that this is not supported in HTTP versions prior to HTTP/1.1. With that said, if you want to have a non-blocking event based web server, you're better off looking at Tornado and Node as suggested.
Comet is a programming technique that enables web servers to send data to the client without having any need for the client to request it This technique will produce more responsive applications than classic AJAX The user must create a request (for example by clicking on a link) or a periodic AJAX request must happen in order to get new data fro the server.
but it's create lots of traffic on your web server. If you want to build chat application in PHP use pusher which is a third party service and easy to use.
here is a link for pusher https://pusher.com/tutorials/realtime_chat_widget
the second suggestion is use ratchet for creating a chat application.
here is link for ratchet http://socketo.me/docs/hello-world
i hope it will help you

PHP - AJAX jQuery Server "Push" System

I am creating a web app that requires a live notification system. How would I set up my server to pull data from a mySQL database and then push it to the browser. I have absolutely NO idea how to do this. If anybody can help, it would be much appreciated! Thank you so much!
EDIT: I should probably be more specific, I am pulling data as in XYZ recently created an account, XZY recently ... Thanks so much!
You cannot push data to a browser, but what you can do is set up your webpage to poll your server every few seconds for updates. An example setup would be:
From within your website, have a javascript function that runs on a timer every few seconds (or whatever interval works best for your situation).
Start that timer on page load.
That javascript function invokes an AJAX call to a web service on your web server (more on that in a second).
On the server side you'll need some sort of system that tracks these events and stores them somewhere such as in a database table with a timestamp. So for example when XYZ creates an account, that would be logged in this "event" table in the db.
The web service called by the AJAX call will then run a query on that table and retrieve all entries since the last time it was called. Then just update the webpage with those results.
It's obviously not 100% "live" as there will be a small delay depending on what time interval you set in the JS timer but it's pretty close.
You can create a push notification service for your website utilizing websockets and graceful degradation to a long polling fallback for browsers that don't support websockets. This does require a healthy amount of technical/programming knowledge.
Some good resources for this are:
http://socket.io (which uses a node.js backend for the web sockets and handles degradation)
http://pusherapp.com (a commercial solution if you don't want to roll and maintain your own service)
For a list of browsers that support websockets, you can search for "caniuse" -- which provides great details to features supported by browser versions
Note: For multi-million user applications like Facebook, I would assume they've weighed the advantages of running websockets for 50+ million simultaneous users and concluded that keeping data consistent across all the nodes connected to the millions of sockets would be too much. I can imagine it would be a logic nightmare to do that on a socket system instead of a basic action sql-like infrastructure. I can't speak on their behalf though, this is simply my assumption. However, you'd be surprised how many sites have been using push and polling systems lately :)

Categories