I have been searching the internet for about two days now, trying to understand how web sockets work, I am relatively new at Javascript and PHP, seeing as I started about two or three months ago.
I am extremely confused about what an Http protocol is, and how to perform a 'handshake' with a server as I have been reading about. So unfortunately it is difficult for me to ask a more specific question than the one in the title.
However, even more than I would like an answer to the question in the title, I would really like a resource that will teach me about web sockets in a thorough way, such as a book or an online tutorial.
Any help is appreciated, thanks.
Sockets in general are just TCP streams that you can send data over. HTTP is built on top of them. WebSockets are build on/in parallel with HTTP, and allow for sending data back and forth to a browser in real-time. Standard sockets can do some of this, but browsers have tight security which makes it tough to use standard sockets to communicate with them.
WebSockets are useful when you need a persistent connection to the server from the browser, for real-time applications, or things like push notifications.
I don't know much about PHP implementations unfortunately, but it looks like there is a library here: http://code.google.com/p/phpwebsocket/
Personally, I'd shy away from doing things like this in PHP because PHP/Apache can be pretty heavy, and since the socket is always open while someone is viewing the page, server resources can be used up pretty quickly.
A lot of people like to use NodeJS with socket.io because then you can use JavaScript on the server and the browser, but really it is up to preference. I would look at Socket.IO and find a language that has a good client for it.
It looks like this question might be useful too. Using PHP with Socket.io
Does this one fit the bill?
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
If not I can find another.
Related
I've been "recruited" so to speak to help work on a web project that is currently written in PHP with an Apache server. We would like to integrate a real-time (or at least something very close to it) chat feature. Scalability is a definite concern, and this type of work is definitely not my typical.
Everything I've read about creating such a chat feature requires the use of "long-polling" so the servers don't get rapidly overloaded and, well, crash. PHP and Apache are not conducive to implementing such a feature, so I've explored some alternatives, like Twisted Python for example.
The website has roughly ~7,000 lines of PHP (i.e., it'd pretty difficult to just straight switch languages for the entire thing), so my question is how can I manage this situation as far as trying to integrate python and setting up a separate server? Or, is this a very bad way to do this? Are there other alternatives that would be better suited? (Sadly many of the PHP Comet, or even AJAX, solutions I've found don't scale in the slightest. Note, the Apache server is not necessarily required; however, any server used must work with PHP and Python etc, short of having separate servers.)
Thanks for the help!
I would use Tornado on the server to write the chat application. Client server communication can then be over websockets. If you use SockJS on the client side you can also support older browsers via long polling. There are plenty of example chat clients written using Tornado. It's very simple to get started and it is wonderfully scalable. A chat server like this can be serving thousands of clients without showing any appreciable CPU activity.
This is an example, possibly a bit over engineered https://github.com/diggidanne/websocket-chat/blob/master/server.py
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
Only yesterday, I was asking a friend of mine how he would go about emulating direct communication channels between two clients through a web server, for the purpose of creating a chat application, but by using solely PHP/MySQL/JavaScript.
He told me that the best way to do this was by the use of SOCKETS, a term I had only heard of until then. This morning I started looking into it for the purpose of creating my chat application, but I'm quickly starting to believe that it's not as easy as I'd hoped.
So my question is this: if I don't have access to my own server (I have a domain hosted on a shared server that I also use for testing purposes), can I still use sockets to achieve my goal? If so, how exactly? (Please understand that I am completely new to the idea)
If not, what other way is there to accomplish the communication channels?
My only idea so far is to simply send periodic requests (AJAX) to the web server the application would be stored on and request any new messages, if any. But this does not seem very feasible.
Thanks in advance for your help!
I think what your friend is trying to get to is implementing Comet for your chat site.
Assuming he's getting you to use PHP sockets to act as a daemon, I highly doubt a shared hosting provider will let you do it.
You could try hanging the PHP script until there's data available. However, this will quickly consume resources on a CGI-based server since the PHP server can't tell if the client is still connected. I know this from experience.
For these kind of things, I highly recommend you get a dedicated server or VPS and write your backend in something like socket.io which automagically handles all your communication problems on both the client and server side. PHP, MYSQL and servers that fork to serve requests are usually the worst case scenarios for implementing Comet since they incur quite a bit of overhead and aren't scalable.
If you can't afford to run your own Comet server, then polling may be your only option. This will be the most resource intensive and least responsive.
I am developing a non-real time browser RPG game (think Kingdom of Loathing) which would be played from within a Flash app. At first I just wanted to make the communication with server using simply URLLoader to tell PHP what I am doing, and using $_SESSION to store data needed in-between request.
I wonder if it wouldn't be better to base it on a socket connection, an app residing on a server written in Java or Python. The problem is I have never ever written such an app so I have no idea how much I'd have to "shift" my thoughts from simple responding do request (like PHP) to continuously working application. I won't hide I am also concerned about the memory and CPU usage of such Server app, when for example there would be hundreds of users connected. I've done some research.
I have tried to do some research, but thanks to my nil knowledge on the sockets subject I haven't found anything helpful. So, considering the fact I don't need real time data exchange, will it be wise to develop the server side part as socket server, not in plain ol' PHP?
Since your game isn't something that's working in realtime you probably don't need to go down the socket route, though it's certainly a viable option. The nice thing about sockets is that updates would be instant without requiring page refresh (or server poll), so you're right to at least consider it.
If you do want to do a more real-time server setup, you might consider using something like Electroserver - this abstracts out much of the setup for you so you don't have to write your own server from scratch, plus it's free up to a certain number of concurrent users if I recall correctly.
Finally, a third option you have is a modified POST approach using AMF. Look into AMFPHP, it lets you call methods on a PHP back-end directly from your flash application. A little bit faster and easier than simply using POST stuff, but not quite as seamless as a socket connection or a specifically built gaming server.
Lots of options out there, it sounds like you are aware of this and kudos for trying to come up with the best approach rather than just rolling with what you know! I hope this helps, let me know if you have any questions.
Here's a link to Electroserver - http://www.electro-server.com/
I'm thinking of building a game along the lines of Farmville - items, events, time management system etc. Options I am thinking of:
1) Flash UI frontend that uses AMFPHP to get all data for the view from a PHP powered backend.
2) Actionscript to power the whole game
Any input is appreciated. My concern with Actionscript is scaling, my concern with PHP is having to build an update system that would need a lot of back and forth xmlhttprequests which might get complicated.
If there's a better way to build something like this, I'm all ears :)
Don't clone/copy Farmville, there are hundreds doing the same thing.
But to your question:
Frontend: Flash
Server: AMFPHP
Backend/CMS: PHP
seems like a good idea.
Actionscript on the frontend side will definitely scale, it has be done a thousand times.
PHP as server and backend part should be no problem, too.
Why you would need xmlhttprequests if you have a NetConnection for Remoting the AMF I don't know.
In this interview "Luke Rajlich" from Farmville mentions using AMF and doesn't mention using XML sockets.
"How do you talk to the backend? Is it Request-response, XHR, long-polling, Flash XML sockets, or "COMET"?
We use a standard HTTP request/response protocol called AMF. The AMF transactions happen asynchronously from the client and if the server sees something it doesn't think the client should be sending, it returns to the client an "Out of Sync" message which tells the client it is in an invalid state and the client reloads itself."
http://highscalability.com/blog/2010/3/10/how-farmville-scales-the-follow-up.html
Since they don't seem to use sockets, I assume they don't use a socket server like smartfoxserver or electro server? Do you think they build their own server, they said they use PHP in the followup interview to the interview linked to above, do you know of any software that will work as a server with all of these AMF connections and PHP--is that what AMFPHP is? (I couldn't find many clear descriptions of AMFPHP online.)
Also, do you know of any good socket servers which work with PHP, it seems like you need to know Java to use smartfox server or electro server, is that correct?
Also, if Farmville uses AMF, would mean they don't use sockets, and would that mean they use polling for changes?
My personal advice:
Backend: Haxe targeting flash9
Frontend: Haxe targeting PHP or neko
Use Haxe remoting for communication, SPOD for database with templo for HTML, or try haXigniter ... I'd personally advise to compile to neko for speed and footprint, but that's up to you ...
write all in one beautiful language ... reduce communication to transparent calls, and database actions to transparent object manipulation.
Me and some friends built argblargs on that exact stack. It's worked great for us, I can't vouch for the scaling into thousands of users, but I don't really think you should worry about that this soon.
Could Farmville be using AMF, perhaps AMFPHP, with a PHP socket server? I'm confused as to whether you would use one or the other, AMF and sockets, are they mutually exclusive? From what I read here, you can use AMF with sockets, is this correct?
"flash.net.Socket is a simpler or, rather, more raw API that allows you to create your own persistent connection but leaves the protocol and communication format up entirely up to you. With the ability of flash.utils.ByteArray to serialize ActionScript objects using AMF you could also use AMF if you wanted to on your Socket so long as the endpoint understands this format."
http://www.mail-archive.com/flexcoders#yahoogroups.com/msg44653.html
However, reading other information such as here they seem to emphasize that AMF and sockets are for different purposes.
Thanks! I'm just trying to figure out all the different possible variations.