JS to PHP Sockets? - javascript

I have become very comfortable with PHP and mySQL over the past couple months, but I have recently wanted to create a game (with database connections) that needs even better responsiveness then AJAX. This is where I came across sockets. I do not want to branch into Node.js (I am more comfortable with PHP servers) but PHP sockets can't be pushed information via JavaScript, which is crucial for responsive user input.
In short, I am seeking a method with the responsiveness of sockets but that can be pushed by the client in JS and received in PHP on server, similar to AJAX but bidirectional and fast.
Note I may be misunderstanding some of these concepts as a new member to this crazy new set of servers. Just correct and direct me please.

To build a PHP websocket server, Take a look at RatchetPHP: http://socketo.me/
It uses a sub protocol, WAMP so your websocket connection will have channels (topics).
Cons: It still uses the version 1 of WAMP subprotocol, the author suggest to use Thruway.
But RatchetPHP is better documented, and let you learn to implement websockets easily.

Related

How would I create a real-time chat using PHP, AJAX and AngularJS?

Is there any simple way to make a real-time private messaging website without having to use node.js & socket.io?
I'm not asking for the code, I just want to get some sort of starting point since I really have no idea how to do it.
You can use Ajax Jquery & HTML to make a chat.
Here is one I found on Github, this might help you to learn how to make one using these coding langugaes.
Github link: https://github.com/Frug/AJAX-Chat
Why do not you want to use sockets? You will be obliged to make requests every second(you say real-time chat) and it will be hard for the sever. How about if more than 100, 1000 or 5000 users are chating ?
You better use socket.io because it avoids this kind of overloading
Writing a chat application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it’s a lot slower than it should be.
Sockets have traditionally been the solution around which most realtime chat systems are architected, providing a bi-directional communication channel between a client and a server.
This means that the server can push messages to clients. Whenever you write a chat message, the idea is that the server will get it and push it to all other connected clients.

If I wanted to create an AJAX chat what communication technique should be used to maintain scalability?

I put together an AJAX chat a while back ASP.NET MVC and jQuery. The javascript would hit the server about every 7 seconds to check for new messages. Obviously this was horrible on performance as the chat grew and included more and more users. The site traffic grew exponentially with so many requests going on. A user could leave the computer on all day and not even be there and they would still be making hits every 7 seconds.
Is there a better way to do this? I have heard of something called "push" but I haven't really been able to wrap my head around it. I think I just need pointed in the right direction.
1.) What is the best way to develop an AJAX chat and have it be scalable?
2.) What is push and how would I just that with jQuery?
1.) What is the best way to develop an AJAX chat and have it be scalable?
I agree with #freakish about the complexity and potential lack of scaling of IIS.
However, there is a relatively new Microsoft option in the works called SignalR which could become a core part of ASP.NET. More details in this related SO Question:
AJAX Comet - Is there any solution Microsoft is working on or supports to allow it to be scalable?
2.) What is push and how would I just that with jQuery?
Partially answered elsewhere, but it's a long-held persistent connection between the server and the client which means the server can instantly 'push' data to the client when it has new data available.
jQuery does support making AJAX requests but the core library doesn't support expose ways of doing HTTP Long-Polling or HTTP Streaming. More information in this SO answer to 'Long Polling/HTTP Streaming General Questions'.
Server push is a technology that allows the server to push data back to the client without forcing client to make many requests (like every 7 seconds). It is not really a matter of javascript but rather good server scripting. The upcoming HTML5 will make it simple due to server-sent events and/or WebSockets. This will be a true TCP connection between different machines.
But if you intend to make a webpage compatible with older browsers, then the most common technique is the long polling. The client sends request to the server and the server does not respond to it until it has new data. If it does then the response is made and the client immediatly after receiving data calls the server with new request. In practice however this requires the server to be well-written (for example it has to maintain thousands of idle requests at the same time) and can become a rather big challenge for developers.
I hope this helps. :) Good luck!
The technique you should use is the real-time persistent long running connections over a web page using WebSockets. You can use this library.
Node.js is becoming quite popular to build something like this and supports socket connections so you could push the data out only when there is a new message. But that would be learning something completely new.
Another nice potential would be to use MVC's OutputCacheAttribute and use the SQL dependency option so your AJAX page could be cached and would only be a new request when a new chat message appears. Also you would want your controller to be an Asynchronous controller to help reduce the load on IIS.
Enjoy, optimization is always fun and very time consuming!

PostgreSQL sockets from JavaScript (HTML5)

I'm looking at options to connect directly--without a web server or middleware--to a PostgreSQL server using JavaScript from a web browser client. On github, I found three projects:
node_postgres
node-postgres
postgres-js
They all appear to be in early but at least somewhat active development.
Do they all do roughly the same thing? Is what they do even what I'm looking for? Does anyone have experience with any of them that could recommend one over the others?
node-postgres was inspired by postgres-js and does roughly the same thing.
However, they both seem to be their own sort of middleware, because they require node.js, which is a server-side JavaScript implementation of a web server. So they would cut out a layer, but still not be the same thing as connecting directly to the PostgreSQL server.
There might be a way to combine the code in them with some HTML5 socket examples, though, to make connections directly from a web browser client.
If you are interested in CLIENT side JavaScript, as the OP's question implied, but you don't insist on owning the server, there is a commercial service that can help you.
The Rdbhost service makes PostgreSQL servers accessible from client-side JavaScript. There is a security system to prevent unauthorized queries, using a server-side white-list and an automated white-list populating system.
It uses plain old AJAX style http requests, provides a jQuery extension to facilitate the querying.
See https://www.rdbhost.com .
There is no secure solution today. One of possible solutions would be htsql:
http://htsql.org/
However there you use web addresses to query, even with https your queries will be plain text!
You should/could use a small webserver to handle requests. Alternativelly you can write an app, or use a local postgres server to handle the connection (in this case you still will need some kind of webserver).
The problem is very simple: your webbrowsers are limited in protocols to talk to the web, and postgres is not on this list. In fact you should not try to overcome this issue, using a server-client architecture is a very good solution. Format your request with JS to make it as small as possible, and let your web-server scripts interpret it into functional sql requests. The answer can be parsed into shorter response, then a sql data transfer, and you just need to interpret it on your side. Since you will create interperers on all sides, you will achieve a higher abstraction then in case of direct db connection, and thus independency towards the backend engines you use.

webgame with simultaneous players

I have seen many webbrowser based games with players playing simultaneously.
Usually after waiting some time you can join a room where everyone is playing or you can play against one other player.
All those games use Flash.
How they achieve that?
It would be very complex to accomplice without Flash?
There are any toolkit (rails, etc) or plugin that provides this functionality?
Or it is just a matter of storing sessions and mixing them ?
Just a quick edit:
I am not interested in Flash or Silverlight solutions
There are a couple options for a JavaScript-only solution. They all involve AJAX of one form or another. (See my answer on AJAX and Client-Server Architecture with JavaScript for a larger breakdown.)
You have a choice between AJAX Polling, Long Polling, COMET, or the upcoming Web Sockets. The first step is to understand AJAX. Once you are comfortable with it, you can setup a polling system (with setInterval) to poll the server for new data every n miliseconds.
It's possible to do it without flash if you're comfortable with ajax and your game doesn't require rapid interactions between users. But in either case, I believe you have to poll the server. You might also want to read about comet http://en.wikipedia.org/wiki/Comet_(programming)).
Can you clarify what kind of game you would like to make? Turn based or real-time?
Since you're not interested in flash or silverlight solutions (which can use sockets and thus scale well with thousands of users) you can use javascript and use ajax to send and receive data.
Essentially you can use ajax like a socket by sending out input then letting the script "long poll" the server by having the server delay responding to it until it has data to send. The only problem is that you can only keep a connection open for so long before it times out (~30 seconds). This isn't usually a problem though since you're passing data back and forth frequently.
I'd research fastCGI (or so I believe it can work like this) and have a game server daemon respond to the requests directly. That way it can open a single database connection and process all of the clients quickly. While this isn't necessary it would probably scale really well if implemented correctly.
At the moment I've been making a proof of concept that's kind of naive. (Less naive than using the database as state and just using PHP scripts to update and receive the database's state. I should note though that for a only a few users and your own database this works rather well. I had 20 clients walking around at 100 ms updates. Sure it doesn't scale well and kills the database with 10 connections per client per second but it "works"). Basically the idea is that I have javascript generate packets and sends them to a PHP script. That PHP script opens a unix domain socket and forwards the data to a C++ daemon. Haven't benchmarked it though, so it's hard to tell how well it'll scale.
If you feel comfortable though I really do recommend learning flash and socket networking. Using Epoll on linux or IOCP on windows you can host hundreds of clients. I've done tests of 100 clients on a C# socket server in the past and it took less than 5% CPU handling constant streams of small packets.
Depends what technology you want to use. Flash can be used to create a game like that, so can Silverlight. They both use javascript to send mouse movements and other user input asynchronously to the server so that the game state can be updated on the server.
An article of flash game development:
http://www.brighthub.com/internet/web-development/articles/11010.aspx
Silverlight:
http://www.brighthub.com/internet/web-development/articles/14494.aspx
Java Applets are able to communicate with JavaScript (e.g. you want your UI to be HTML&CSS). So in theory you could implement your network code in a signed Java Applet. In this case you would not be limited to the plain client-server model.

AJAX and Client-Server Architecture with JavaScript

I have to program websites, but I rather don't like the static HTML nature. I prefer more of a client-server architecture.
Now I've figured, that with XMLhttp, you can basically dynamically update your page and send/request for information/action to/from a server. So this would basically cover the client area.
But to complete a client-server architecture, it is necessary for the server to send/request information, too, without being queried.
Is there any way, for example for a chat server, to send back a received message to all clients (the clients use a web browser) without that the clients have to query in a fixed interval? I want to implement that one can see while you type something in.
There are several different ways to accomplish this. Some of them are already answered here, but I wanted to include a few more as well as my thoughts on them.
1. Polling
Frequent requests are made to the server to check for new info. This is the worst way to do this, but probably the easiest. If your site will have a low number of users, it might be worth doing it this way.
This can be accomplished by using setInterval(myFunction, n) in javascript to send XMLHttpRequests to the server every n milliseconds. Then, on the server, you respond to this with your new info, when you have it, or some message that implies no new info.
2. Long Polling
When the page is loaded, it makes a request to the server for new info. The server holds the connection open until there is something to send back. This method reduces the amount of network traffic used, but increases the resources used on the server. You can use this for a small number of users, but it doesn't scale very well.
The easiest way to do this is to have the page that handles the AJAX request simply wait for new information to be available, then respond. This can tie up a lot connections on your server. So, use with care.
3. COMET
COMET is basically long polling, but the server is setup properly for it. It knows that these connections aren't "real" and it uses less resources to handle them. This is a great solution for this problem, but it requires that the server is explicitly setup for this purpose. There are COMET servers and COMET addins for other popular servers, but it will require some setup and sometimes some money.
Implementing this on .NET isn't the easiest thing in the world. You can pay for solutions, try to find someone else's code that does something similar, or try to write it yourself. I've not found any decent free solutions for this. If someone else has, please comment.
4. RIA
Another solution would be to include Flash, Silverlight, or Java Applet on your page. People often do this by using a 1x1 object so that they can use Flash or Silverlight to talk to the server. If you don't mind adding the dependency, this is a decent solution. If you already know Silverlight or Flash, it could be relatively simple to implement.
You can find tutorials on the internet for each of these options.
5. Web Sockets
If you are on the cutting edge, you can look into Web Sockets. It's only available in the latest builds of modern browsers. It was part of HTML5, but it might be its own spec now. Regardless, it means that older browsers won't be able to handle it. But, if you don't mind limiting yourself to the latest of browsers, you can use this amazing feature.
I believe that Chromium is the only browser that currently supports it. However, there is work being done to implement this in Firefox and WebKit.
I'll spare you the controversy and simply say that this does exactly what you want it to. The Abstract of the spec says it all.
This specification defines an API that enables Web pages to use the Web Sockets protocol for two-way communication with a remote host.
Special Mention
If you are interested in the world of Node JS, you can't go wrong with Socket IO. It will implement the best of whichever technology is available to the browser.
Conclusion
The best option is Socket.IO on Node JS. However, for an ASP.Net solution, go for COMET or Web Sockets, if you can. Otherwise, using Flash/Silverlight isn't terrible. Finally, polling and long polling should be last resorts. You could always support one of these, then fall back to another if there isn't support for it in the client's browser.
Yes, you can use COMET.
The client has to tell the server when the client-user begins typing. You've got a couple options here.
Frequent requests from the server for the latest activity. This would be taking place for each user involved in the chat. The same request could be used to send user-specific activity to the server as well: "Jonathan is typing..."
Long-polling. This essentially requests information from the server, and the server keeps the connection opened until it has something to send back. So your requests are minimized, but your connections stay opened longer.
Depending on your traffic, type of data being transmitted, server-environment, and many other factors, one of these options may shine more than the other.
You can use Silverlight for push notifications. Look at PollingDuplexHttpBinding. Since you are using ASP.Net MVC, adding Silverlight will be easy.
Look at this page for more information.
Based upon the REST architecture the html system is based upon, the servers role is to simply act as a resource for the client to pull from. I am generalizing but there are tools to implement this type of action on the client side, rather than on the server side.
You are better off writing/using a library that can request updates from the server periodically. You can encapsulate these types of requests in a javascript object that can fire events. This way your client side script can act like it's getting notified from the server. Review some common stuff with COMET you can probably find some tools to help you client side code.
HTML 5 has some tentative attempts at this type of functionality, but if you want your app to work on older browsers, your better off using more stable methods, like AJAX requested updates.

Categories

Resources