Current Project Setup
I've been working on a web-based chat, similar to Facebook chat. At the current state, I listen for incoming chats and check for new messages in an existing chat is by doing...
setTimeout(function() { listenForIncomingChat() }, 500);
setTimeout(function() { checkForIncomingMessages( ...params... ) }, 500);
... so doing the setTimeout() makes sure these functions are always running. Depending on how many chat windows I have open, Firebug's console can go crazy with POSTs to the server :)
Obviously this is really inefficient, but it is the only way I could get things to work. Now I'm looking for the ways to make it better, to do it correctly!
Some Research
Now, I have heard about Comet Programming and that this is the way to open a long-lived HTTP connection with the server, but I'm not familiar with the technology or the ideas behind Comet. WebSockets for HTML5 is probably even better, but since that is not in full swing nor is it supported by all browsers, I'll stick with what works.
According to Wikipedia, there are several ways to develop with the Comet style: Streaming (hidden iFrame, XMLHttpRequest) or AJAX with long polling (XMLHttpRequest, Script tag). However, I don't know anything about this. I've also read about the AJAX Push Engine (APE) and it looks cool, but I don't want to use a third-party for the time being.
I've recently stumbled upon WebChat 2.0 so I'm going to be looking through the source code to try and understand how it all works.
On to the question(s)
So where can I find example code/tutorials on how to get started with this kind of project? How would I implement the Comet technique? How do I set up the long-lived HTTP connection with the server?
Here's an example of a chatroom using node.js, source code here.
I believe the client uses polling, but this example is interesting because the server side is in JS too, and node.js is efficient for this type of stuff.
Related
In my company, we're using Spring Boot to implement backend API and React to implement frontend including Web interface and Android/iOS apps.
Since our product is an Enterprise software, customers actually have to pay to get the latest backend API to deploy on their own servers. However, our mobile apps are regularly updated on the App Store. This leads to a situation where the mobile apps on end-users' devices may be the newer version while the backend API on the customer's machine is the older one. We plan to support up to 3 minor version backward, meaning FE 5.4 will support up to backend 5.2.
The backend does have an endpoint to return the current version number. However, I'm a bit clueless as to how our frontend implementation can maintain backward compatibility with older API versions as we add new features and may introduce breaking changes in backend API.
I completely understand there might not any beautiful solutions for this problem. I'm hoping if you've gone through this pain, you can share your experiences about what you've tried, the final approach that you took and the potential pitfalls to look out for.
I'm sure myself and other people who's running into this issue would be really grateful :).
Your solution will be similar to any frontend solution that uses Feature Toggle but I can already imagine that it will not be pretty.
Basically inside your code you'll have a lot of if/else statements or some form of wrapper that does the same underneath for every piece of UI/logic/functionality that is a breaking change on version upgrade.
I'd suggest that for every layers that you have (UI, logic, API call) you should start to have switches based on version returned by backend. You'll end up with a lot of redundant looking codes and a lot of codes that looks like this. (if you support only two versions. Use switch if you have more versions)
render() {
{version === "1.0.0" ? <VersionA /> : <VersionB/>}
}
You can however, write a utility method that wraps and returns different components based on versions. By doing that you can more easily remove components that you no longer need to support in the future.
const versionSwitcher = (version, ...Components) => {
switch (version) {
case "1.0.0":
return Components[0];
case "1.1.0":
return Components[1];
}
}
This of course, increases complexity throughout all layers but given your case I can't see it being simple. A good thing to do is to try to keep your own viewModel and never pass response from API directly into component. That reduces the coupling between API and your components and will make this a little easier.
I have a VS 2013 Lightswitch HTML Client application to which I've added a button that makes a Web API REST post. This basically 'refreshes' the data in the table from the original upstream source. This is all working correctly, but the operation takes a few minutes, and I want to report status to the user as it runs.
Right now, I've tried attaching a simple Refresh when the post returns as follows:
$.post("/api/data/", "Refresh", function (response) {
screen.getData().then(function (newData) { screen.reQuery(); });
});
This doesn't actually seem to do a refresh (screen.reQuery is apparently the wrong call), but the better option would be to instead have the server show progress of this long-running application.
One thought I had would be to have the server call return data in the form of "percent done" in the response as it processes it, but I don't know if this would be delivered to the client piecemeal, nor the best way to display this to the user in Lightswitch.
I'm open to other third-party libraries that might help with this, but I'd like to stick with WebAPI for commanding instead of adding something like SignalR for now, if possible. Thanks!
In general this seems like not the best idea to run operations that takes minutes on the server.
A reasonable alternative is to create a single call, that will in turn create multiple Web Jobs (see Azure Web Jobs for more info). The Web Jobs will be broken to smaller individual tasks, and your html will query the web jobs rather than your Web API.
I am indeed new here, but I have been reading the responses for.. since I've began programming.
I am still new, and absolutely fresh out the womb when it comes to networking. But I'll keep this brief so you can give a conclusive answer.
I have a webserver and a domain name. I would like to use websockets to make an environment in which both players can move at the same time on the same screen. For example, if the mouse controlled a dot, and two people connected to a global "world" then a single person could see the dot of the other person in real time. An example of something like this would be rumpetroll.com.
I don't expect to get a whole lot about how to design a game like RuneScape (although I think that the idea is almost the same). I just want some in-depth explanation of how to get this cool little interaction going.
Any links to how to program to sockets would be GREATLY appreciated, because all I can find on the internet is the concept. Nothing on the mechanics and what each command may do.
Anyway, thanks guys.
You will need a server and a client. I am assuming you know JavaScript, so I will provide an example that uses it on both sides.
The server
You will need nodejs, install it following the instructions on the site.
I will provide examples using socket.io, since you asked for websockets, but keep in mind that there are also other solutions, like Faye, which is worth looking at.
Put yourself in a new folder, run npm install socket.io, this will download the required code for the server; then paste this code in a file named server.js
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
socket.emit('new-connection', { message: 'we have a new user!' });
socket.on('message-from-client', function (data) {
console.log(JSON,stringify(data));
});
});
Start the server by typing node server.js, you should see info - socket.io started in the console.
The client
Paste this code in a file called index.html and open it with your favorite web browser
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
socket.on('new-connection', function (data) {
alert(JSON.stringify(data));
socket.emit('message-from-client', { message: 'hi' });
});
</script>
As soon as you navigate to http://localhost:8000 you will see two things:
an alert greeting you
a message in the console where you started the server
this will happen each time you navigate to that url, try navigating to it with two different browsers or in a incognito / private browsing window. Each time you should see the alert and the message.
This is the basic setup. From here you could complicate things as much as you like to, if you will be using this solution consider passing data around in JSON, as I showed in the examples.
Where to go from here
As you can see it is really easy, if you want to show a dot, that will appear for all users, bind the client mouse movements to a function that will send the position to the server and have it broadcast to all the other connected users (should be something like socket.broadcast.emit but look into the docs as I'm not sure), or you could simply send an event, something like updated-mouse-position which will have a function bound to it that will handle the graphical part.
Hope this helps, feel free to add comments if you have doubs / problems with the basic configuration.
I want to create a website like Google Image Labeler, in which people can tag images.
but this is my first serious web programming project and my problem is that I don't know what are requirements for doing this job.
In this site what I have to do is First : pair people randomly and second : I need to send each session information to server asynchronously ( not only client to server [ AJAX ], but also server to client [ by using comet I guess ] )
I have Python and PHP programming experience and also I'm familiar with AJAX and Javascript. In my 2, 3 days journy(!) for finding suitable tools to doing this project I encountered to lot of stuffs : websocket, jquery, comet, socke.io, nod.js and a lot more which just made me so confused.
in fact I'm looking for a good reference helps me on where to start and what to do. ( or you can think of it as : what is best approach for starting asnyc web programming )
thanks a lot in advance
OK, after a lots of trying I got here :
to start async web programming , first of all you need to get familiar with AJAX, it's not that hard . you can earn all you need from w3schools.
after that the best choice you have is jquery . there is lots of incredible things you can do with it . one of it's capabilities is that you can send and receive data using ajax without reloading the page . To get familiar with jquery live page manipulation you can check How to Create A Simple Web-based Chat Application.
Also you can use some of html 5 technologies such as SSE ( server sent events [ more convenient ] one directional connection ) or websockets ( bidirectional connection, useful for web game programming )
In order to pair people you can use Mysql database as a medium to hold each new user's information and after that pair them using an unique id , such as session id . obviously you can use files as a medium too .
That's almost all you need to create a live updating web site , but if you want to do it much more professionally and in the server side, you can look at node.js ( server side javascript, an event oriented programming ) or twisted ( a python frame work ).
This is all I learned in my way .
Sorry for unwanted mistakes .
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have to write a new web application and currently am in the process of deciding on the architecture , there are several things i know i want to be able to do :
All machine must be symmetric , i.e. : commodity machines no custom build servers (aws)
I want a ReST API that is seperated from the UI as i allready have three clients for the API : mobile applications , the web site and a server from a 3rd company waiting for the product to be build
it needs to able to scale horizontal (a but of a repeat of 1)
Easy to maintain : no time to learn new languages , more available candidates but willing to adopt new technologies
here is the basic architecture i've come up with :
frontend combining of nginx+nodejs+expressjs+YUI ,
api : nginx+tomcat+spring framework stack (rest+Security+core+aop)
the frontend will talk to the api with oAuth 2.0
nothing exciting about the api i've done it before , i know it works and works well would have loved to put some scala flavour but i don't have the time .
my main concern is the frontend : nodejs is insanely exciting and i've been playing around for some time also love the fact it's in JS , but i'm afraid about navigation+templating+sessions (for authentication only : stateless,stateless,stateless)+logging+debugging of it , if it works it works well but it's not a mature enviourment to develop in .....
anyone here developed a full frontend with stack or subsets of it ? any other suggestions to choose from ?
thanks guys .
but i'm afraid about navigation+templating+sessions (for
authentication only : stateless,stateless,stateless)+logging+debugging
of it
navigation? Not sure what you mean here. Use hyperlinks. AFAIK there's nothing in node like Rails' form_for() type helpers, but those were never that interesting to me. If you want something like Rails style before/after filters, say for requiring a logged in user, connect does this great.
app.all('/app/*', requireUser)
That will call requireUser for any path starting with /app. Inside requireUser you can make sure req.session.user is there (and maybe has proper authorization). If so, you call next() and the middleware responsible for actually generating the response is executed. If the user isn't logged in or is not authorized, you can generate a 30X redirect response and don't call next(). Done. There's a great example exactly like this in the express.js guide. Search for loadUser. This design is really elegant, IMHO.
templating? Uh, node.js has as good or better templating options than any other platform. Try jade or any of a dozen others. You can use the same templates on the server and in the browser, which is a nice win. Check out this video of Dav Glass using YUI widgets on the server side in node.js since you like YUI.
sessions? Connect sessions. Taste great. Less filling. What's the problem?
logging? Winston works for me. There are also fancier libraries as well I think.
debugging? node-inspector gives node.js (IMHO) the best debugging support available. It debugs with chrome's inspector and is every bit as awesome as debugging client side javascript. I can also debug server side unit tests when running via jasbin.
Here's an answer to what companies are using node.js in production.
So if you got problem with testing then you just misunderstand some features of Node.js and express. For example you can use something like this for testing:
app.get('/route', function(req,res,next) {
require('./controllers.js').method(req,res,next)
});
Then you need to drop cache with all files required in your controlles.js:
if (require.cache[__filename])
{
var del = false;
for ( i in require.cache)
{
if (i == __filename)
{
del = true;
}
if (del)
{
delete require.cache[i];
}
}
}
So now your controller will updated instantly to current version when request pass.
To understand how does nodejs require work just try this:
require.js
module.exports = {};
main.js
var x = require('./require.js');
x.tell = true;
var y = require('./require.js');
y.tell = false;
console.log(require('./require.js'));