I have experience with Php from school. I know that if you want to build a website in php you simply need an host and write page with the .php extension.
You might need a database for crud operations of course.
Now I was trying to shift from php to node. I just can't understand how node works. It's probably my brain that can't reach the ha ah moment.
So first of all, let's say I want to create a website with login, sign up, different pages etc.. And I want to use node as server side language. In php you just needed to write in the actual page, upload on the server and it dose what you ask..
How this is possible in node.js? Pages are in javascript and javascript is editable from the browser becouse is clientside. So how do i write node and where? I can't understand how does it work...
How to chose a good host for node? I remember websites like Aruba hosting that just gave me space to upload my php pages. How does it work for node? Are there particular host?
Sorry guys I know it is maybe a dumb question. But I need to get out of this limbo..
Lets start by splitting up your questions:
So first of all, let's say I want to create a website with login, sign up, different pages etc.. And I want to use node as server side language. In php you just needed to write in the actual page, upload on the server and it dose what you ask..
First we have to understand WHY PHP works like that. According to TechTerms:
PHP Stands for "Hypertext Preprocessor." PHP is an HTML-embedded Web
scripting language. This means PHP code can be inserted into the HTML
of a Web page. When a PHP page is accessed, the PHP code is read or
"parsed" by the server the page resides on. The output from the PHP
functions on the page are typically returned as HTML code, which can
be read by the browser. Because the PHP code is transformed into HTML
before the page is loaded, users cannot view the PHP code on a page.
This of course, is the original purpose(and still is) of PHP, embedding server-side code in HTML without returning the source and only the intended output, thus it's name Hypertext Preprocessor.
The most classical example, is trying to return a custom message inside an HTML element:
<html>
<body>
<div> Hey <b><?php echo $username ?></b>, how are you today? </div>
</body>
</html>
The output would look something like this:
Hey RavenMask, how are you today?
This is PHP. There are of course, several frameworks available that do change the way you interact with PHP, like the MVC model that Laravel uses.
But now lets move on to NodeJS.
Node is very different from PHP, but still share equal concepts, like both being interpreted, and i believe this is where your confusion started, you probably thought that the code bellow was equivalent of PHP:
<html>
<body>
<div> Hey
<script>
document.write(`<b>RavenMask</b>`)
</script>, how are you today? </div>
</body>
</html>
And in some ways, it is, for client side.
NodeJS is a server-side runtime enviroment, in a more simple-to-understand comparison, NodeJS works exactly like C, Java or C++(Node does not need a compiler like GCC thought, it works using a JIT compiler, but that's for another question).
While PHP is a language designed from the ground to run over a webserver and become easily embeeded on HTML, Node on the other hand is designed more like a traditional language, so, for achieving a result like PHP, a LOT of steps are required, just like you would need with C, C++, Java and any other language.
In Node, to achieve what PHP does, you would need:
Creating an HTTP Server.
Creating an templating engine to mimic what PHP does inside HTML.
Luckily for us, all those steps have been already implemented in battle tested modules(and even in the native NodeJS default library!), so, the most barebones example that you can get is this:
const http = require('http')
// Here you're creating the HTTP server, like Apache
const server = http.createServer((request, response) => {
const username = 'RavenMask'
// Abuse templating strings!
// Respose.end means: Give this back to the client and end the cicle of the request
response.end(`
<html>
<body>
<div> Hey <b>${username}</b>, how are you today? </div>
</body>
</html>
`)
})
// Here is where you create the event loop for the HTTP server
server.listen(3000, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening`)
})
Go on, save this file as index.js and on your terminal type:
node index.js
Then go to localhost:3000 on your browser and voilá!
This of course, is NOT production ready, so be careful.
To wrap it up, if you're still interested in Node, the steps you need to take are:
Understand how Node works, including its architecture and the most important, the event loop.
Use and abuse frameworks and modules. The example i gave you above, if you tried to expand it, would cause a lot of suffering and pain due the way it's designed, but it's fine so you can learn. Using frameworks and modules, you get battle-tested, community contributed code that can make your life easier, safer and production-ready, one good example, is creating an HTTP server with the Fastify Framework.
Don't give up: Learning a different language sure is hard, but can give you a lot of opportunities on the market and you can learn a LOT from looking things from a different angle, you usually end up acknowledging mistakes you do on another languages by looking on how things work from another.
Related
Not long ago , we used to have server render pages and then React came for client side rendering and single page application.It introduced virtual DOM's and changed the way we write our code.
We require all these react libraries and install them as dependencies before writing our codes. Now we can break into many components , have many css and scss files including images. But at the end we will build the files, make compact bundle and serve from build folder.
Express get route
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
Heres, What I have understood :
Build folder is the place where webpack combines all the files and create minified bundle ready for deployment. That file is basically simple HTML and JS files which every browser can understand. As all the browser doesn't understand ES6 and much more, we have to convert all these files into plain language that every browser can understand.
Also, webpack-dev server is only for development purposes and we won't be running it into production.
Is virtual DOM/Real DOM just for development purposes? or
are those react libraries also trans-piled while building the minified files? If later is the case , react is run on background mode on client's browser? I want to know how react takes care of client side routing after the building the app.
How do you manage github repositories for Node-React app? Do you keep two different repositories one for front end and other for back-end? Whats the industry standard?
If you keep two repository, how do you deploy the front-end code? As you can't run the webpack-dev-server into production. Nor you can specify the public static (build folder) in your back-end(express server) as they are separated in two repos. How does, either the integration of these two repositories take place( lets say we have two AWS EC2 instance, one for each) or front-end get served from the front-end repo??). Can you actually use something like npm serve in production ??
what am I trying to do ?
I want to deploy my node-react app on AWS. I have only one repository on github. I have one folder "client" inside my repo where all the react code sits with its package.json file. All the other files for server are inside root folder (server doesn't have its own folder and files are scattered inside root folder). So there are two package.json files, one inside root folder for server and one inside client folder.I am planning to run my-node app on a docker container.
Please help me understand the core concepts and standard practices for code hosting and deployment keeping large scale enterprise application in picture.
I would not go into explaining all the points in your question here because, #Arnav Yagnik and #PrivateOmega have both done a brilliant job at explaining most of them. I would definitely recommend you to read their answers properly and read the links provided for more information before reading this answer.
I would like to address your question of deploying a Node-React application. In production, generally, we have different deployments (or "repositories" as you mention in your question) for both the front-end (React) and back-end (Node). This allows your back-end to sit in an EC2 instance, for example, with auto-scaling to make sure that it can cope up with all the requests coming in.
As mentioned in the previous answers, and in your question as well, webpack compiles and minifies the React files into simple HTML and JS files, which most browsers can run (I'm not going to explain VirtualDOM here because it has already been perfectly explained in other answers). You would then take these minified files and serve them from an S3 bucket for example, because again, it is a single page application (also discussed in the other answers) and the business logic is already in the minified JS files and its just simply sending all requests to your back-end server.
Now for front-end, you can use TravisCI for example to deploy the build folder (the one you talk about in your question) to an EC2 instance and serve your files using NGINX or if you can configure a CDN deployment properly, you can serve the files from an S3 bucket for the most optimal performance.
You can think of serving the React application like sending a cryptic block of code to your user's browser. Now you can deploy this cryptic block of code to a publicly available S3 bucket, and serve it from there. Again, because of webpack and minification/uglification, no on would be able to make any proper sense of what your original code was, remember that you can still access all the code in Chrome's Sources tabs for example.
I would like to address this with different approach.
Server Rendered Pages : The concept has not changed, server when encountered with a DOC request it has to respond with a html. Now HTML may or may not contain scripts(can be either inline or a external server address). In case of question's context you can still ship HTML where it will download scripts that you have written(may include react or not). for most cases you can ship empty html with scripts tags which will download the scripts over network and execute them which would contain all the rendering logic.
To Answer your questions :
1st : There is no background mode in a single threaded JS(unless we want to talk about workers but we can leave them out for this discussion). By writing in code you are not interacting with any DOM. You are instructing your components(extended by React) when to change their state and when to re-render(setState). React internally calculates the virtual DOM and compare to Real DOM to calculate actual changes that are to be made on Real DOM(this is very abstract answer, to get more understanding please read react docs, Baseline here is you are not interacting with any DOM just instructing React core library when to update and what is the updated state)
2nd : If you want to support SSR(server rendered pages). I would suggest to make 2 folders , client(this would include all client components and logic) and server(would include all server side logic) with different package.json as packages differ for both applications.There is no such industry standard here, what floats your boat should work but generally making directories based on logical entities should satisfy separation and maintainability, if in future you think you want to fork out server and client in separate repos , it would definitely make the process easy.
3rd : You shun running webpack-dev-server in production. Files are generally not obfuscated hence payload is heavy(not to forget your written code is out there). Even if you want to make different repos, server can spit out html and html can request scripts with your client server.
How to deploy : Deploy your code and run :
node server/app.js
and in app.js you can write the location block what you have mentioned.
P.S. : If you just need a server with that location block. do you really need a express server? You can upload the client build to a CDN and route your domain to serve index.html from the CDN(s3 bucket can also be used here)
I would like to start off with clearing up the terminologies as much as I can.
Like you said server rendered pages was a more prominent standard in the past, but it hasn't changed at all with the introduction of React, because even React has the support for Server rendering or SSR, which means HTML pages are generated at server side and then served to clients using browser.
And client side rendering means, a HTML page is loaded to browser and then javascript code renders things on top of those HTML pages and make them interactive.
And single page application concept is that we have only a single HTML file or base HTML page on top of which based on user interactions and data from server it is rewritten continuously.
Virtual Dom is an amazing concept introduced by React. React library code recreates the structure of all elements(called DOM elements) of a HTML page in the memory in a tree form. This enables React algorithm called Fiber to reconcile appropriate changes as per route update or any other changes first on this tree like structure before translating them onto the real elements in the HTML page.
Babel is a transpiler to transpile latest features that browser engines haven't started supporting to code that they can understand, usually ES6+ code into pre-ES6 because all browser supports that. In React application, if you have written application using JSX syntax, babel supports transforming JSX into normal javascript also.
Yes, breaking up of pages into many components is possible due to compositional nature of components by React which means we can build complex things by combining small and more focussed things.
At the end before serving it to end users, we can't have web application lag due to the huge size of code, so during the build process, things like minifying(removing whitespace etc) and other optimization like combining multiple javascript files into one etc are done, and then compact bundle is served from build folder like you said.
Yes, build folder is where webpack does the minifcation and combination to create a bundle as small as possible. It is basic HTML and JS files that is understood by every browser, and if the code contains something that a particular browser doesn't support, appropriate support code or something called polyfill is also bundled with it. Technically you can't say browsers only understand pre-ES6 code because a lot of browser engines have implemented plenty of ES6 features already.
Webpack dev server is just used to serve a webpack application over a port like a node.js server and gives us features like live-reloading which is needed when you constantly make changes to your application codebase and it isn't needed at production because like we said previously, at production time it's just HTML and JS and nobody ever makes any changes on these files.
Virtual DOM is a memory representation or concept used by React Code just like we have stacks and queues and it not just used at development time. Yes and No. Because I think appropriate parts of react source code which is required to run the application would also be bundled before generating the production bundle.
I would say, don't have a preset way of things, because it is totally upto the developer and the team, because I have seen people using 2 seperate repos because frontend people work on frontend things whereas backend people work on backend things. But there's also a case when everyone's a fullstack developer and you can Technically have it in a single repo with a single package.json and use the backend to serve the frontend files and you have to manually install each react dependency and cannot directly use CRA or create-react-app like generator.
What has 2 repositories to do with front-end deployment in production? You don't need to run webpack-dev-server to server files in production. You can create a production bundle and then setup any http server to serve the generated bundle.
Regarding your current scenario I would say instead of having 2 package.json, you can go with a single package.json and install all dependencies together or go with a monorepo approach using something like lerna or yarn workspaces.
But for a total beginner I would suggest 2 separate repositories to encounter less problems.
And a bonus point if you are not aware, you can write React in pre-ES6 code and also without JSX as well.
1) virtual DOM is basically to say that you are calling a function of react not the actual function which does manipulation on the real DOM
like this one
document.getElementById("demo").innerHTML ="Helloworld"
modifies the actual dom
but this
ReactDOM.render(
<HelloMessage name="Taylor" />,
document.getElementById('demo')
);
if you see this properly you aren't doing anything directly on the dom you are just giving the react function control to do things , internally react take cares of modifying the that dom element demo whenever the react wants to re-render it based on its own logic which is what they claim as optimized which is why people use it in first place. Yes when you build your code with webpack it does include react in it which is part of that minified code, so if you see any of the error stacktrace in development you do see react is the starting point for it
2) I think its a choice to be made, as there are not restrictions on this
3) Coming to deployment , In general if you want use nodejs you might choose expressjs server type of deployment but otherwise generally its better to use a high performance server like Nginx or Apache or else if you just don't want to get into this whole drama of things people generally use heroku based deployment or else people are using special platforms like netlify,surge.sh these days (its super easy to deploy on these platforms).
I believe others have done a pretty good job explaining the React Virtual DOM. In a simple and practical way, I’ll attempt to explain how I (would) manage the deployment of a dynamic website (including medium-sized enterprise systems) using NodeJS and React. I’ll also attempt not to bore you.
Imagine for once that React never existed and that you were building a traditional Server-Side Rendered application. Each time the user hits a route, the controller works with the model to perform some business logic and returns a view. In NodeJS, this view is usually compiled using a template engine such as handlebars. If you reflect for a second, it becomes obvious that the view could be any html content which is then sent back to the browser as a response.
This is a typical response that could be sent back:
<html>
<head>
<title>Our Website</title>
<style></style>
<script src="/link/to/any/JS/script"></script>
</head>
<body>
<h1>Hello World </h1>
</body>
</html>
If this response hits the browser, obviously “Hello World” is displayed on the screen.
Now, with this simple approach, we can do powerful things!
OPTION 1:
We can designate one controller to handle all incoming routes app.get("*", controllerFunc) and render one view for our entire server.
OPTION 2:
We could ask multiple controllers to handle different routes and render route-specific views from our server.
OPTION 3:
We could ask multiple controllers to handle different routes and generate pages on-the-fly (i.e. dynamically) from our server.
If we were building a traditional web application, option 3 would be the only reasonable standard. Here, pages are generated dynamically for different routes. However, with option 1, we can produce a quality Single-Page Application where the response sent to the server is an empty html page but with the built JS script that has the ability to manipulate the DOM – Yes, React! Here’s what such a response might look like:
<html>
<head>
<title>Our Website</title>
<style></style>
<script src="/link/to/any/JS/script"></script>
</head>
<body>
<h1>Hello World </h1>
<div id="root"> </div>
<script async type=”text/javascript” src="/link/to/our/transpiled/ReactSPA.js"></script>
<!--async attribute is important to ensure that the script has access to the DOM whenever it loads. This also makes the script non-blocking -->
</body>
</html>
Clearly, we’re giving all the responsibility to the generated SPA and all routing logic is handled on the client-side (See, react-router-dom). On the server side, we can introduce the concept in option 2 and tweak NodeJS route handlers to listen to another specific route for any REST API communication. If you’re familiar with NodeJS, the order in which routes are registered either by app.get() or app.post() matters.
However, using option 1, we can quickly become limited and only able to serve one Single-Page application from that server. Why? Because we have asked one controller to handle all non-API incoming routes and render one view. We also risk serving an unnecessarily bloated JS file. Users are served the complete website when all they probably wanted was just the landing page.
If we look to the option 2 though, we can tweak things a lot more and serve multiple Single-Page Applications for different routes, all from our server. This approach helps to reduce the sizes of the JS build being sent to the browser. A typical example would be a website that has a welcome page (or an introduction directory), a login page and a dashboard.
By assigning controllers for different routes, we can build SPAs uniquely for those routes. SPA for the intro page, another for the login page, and then another for the dashboard. Yes, the browser would have to load while transitioning between the three, but at least we highly increase initial render time for our website. We can also use the more secure option of cookie for authorization rather than the less secure option of storing session tokens on localStorage.
In a more advanced setting, we could have dynamic websites with different React components rendered as widgets within the dynamically generated page. Actually, this is what Facebook does.
The way to build such SPAs or components is pretty simple. Start up a react project and configure webpack to render the production-ready JS file into your preferred public static directory within the server-side repo. The <script> specified in the view can then easily load these built react components since they exist within the scope of the server-side’s public directory.
In essence, this means one repo with several client directories and one server directory where the destination of the production build files to be generated by webpack for each client project is set to the server’s public static directory. So, each client side’s directory is a project (either full SPA or simple React Component as a widget) with it’s own webpack.config and package.json file. In fact you can have two separate config files – production and development. Then, to build, you use npm ~relevant command~ for either production or development build.
You could then go ahead to host it the way you would host any NodeJS application. Because, the main application is the NodeJS - that's where the server is. Replace NodeJS with PHP and Apache/NGINX, the concept still remains the same.
We are currently trying swiftype and wanted to see how to Crawl our website that has javascript frameworks becauase there are async calls.
I created a engine and was able to run a crawl based my sitemap, but instead of reading the actual content, it is reading my Angular js code.
For eg:
if have an angular code something like
<div ng-class='grey title'> {{ctrl.title}}</div>
and if this data gets binded on page load, instead of reading the title, it reads the actual code as {{ctrl.title}}
so when i search, the page returns something like
"This article is about {{ctrl.title}} . We take you through.... "
Any idea on how to make it compatible with js frameworks?
You can use a "headless" browser through i.e. Playwright.dev. "Headless" means it doesn't have a GUI. Since it's actually a browser it'll interpret the page correctly. It can be started from a JavaScript that runs server-side. Check out Web Scraping : Handling AJAX website part I and the code on GitHub: introWebScraping.
{{mustache}} is, in my opinion, a great template library. The question I face is whether to use it in the client-side, or in the server-side.
I am developing an online magazine that will have a main page with one big article and the the rest of its articles in smaller size underneath.
E.g.
+-------------------------------------------------+
| |
| Big Article Image |
| |
| |
+-------------------------------------------------+
Title
Author
+------------+ +------------+ +-----------+
| Image | | Image | | Image |
+------------+ +------------+ +-----------+
Title Title Title
Author Author Author
...
Server-side option
Using {{mustache}} in the server-side, as a PHP library: when the browser asks for the page, the server will complete the template and send it back.
pros:
Loading times will be better. The browser, once it has received the html code will know which other resources it has to ask the server for.
cons:
It will be difficult to integrate with client-side {{mustache}} because when the template is parsed, all the "mustache-tags" that were not matched are removed (I do not know if this can be easily and cleanly avoided).
I do not like to modify the interface from the server-side, I rather do it from the client-side, thus the 3-tier architecture seems more clear (you might differ with this).
I do not have previous experience with server-side {{mustache}}.
Client-side option
Instead of plain {{mustache}} I usually use ICanHas.js, which wraps {{mustache}} and makes it incredibly easy and comfortable: when the browser asks for the page, the HTML is sent, containing all th js code to ask the server for the JSON which contains the title, author, and filename of the image.
pros:
Enhances 3-tier architecture.
Things like infinite scrolling (an other ajax stuff) are super-simple to add.
cons:
Load time is worsen. The browser will need to receive the code, make a request for the JSON, and then ask the server for the resources discovered in that JSON (like the image filename).
Question
Which one do you think, from your experience, is the best solution? Why?
I'd like to add a couple of points to your pros & cons.
Client side templating is more error-prone than server side
With all kind of browsers, versions, devices and security settings, things can quickly get messed up. The more javascript and client-side templating you have on the page, the more likely you'll have some users getting a screwed up page. Think of IE default compatibility settings for instance, a pain. With server side templating, you just have to check it once and be happy.
Client side templating is typically harder to debug than server side
First, you typically don't notice it when a client gets an error in the browser, except if you have some reporting system. Then, you get some cryptic one-liner error message. On server side, on the other hand, you can automatically monitor errors and have nice stack traces where it happen. Sweet ...saves a lot of time.
Probably better SEO with server side templating
It is straightforward for bots to accurately parse static or server generated pages. For pages full of client side templating, I don't really know what you'd get, hence the indexing might suffer.
Loading time is quicker with server side templating
Especially for mobile with low end phones, client side templating might make a noticeable difference. Especially if you have to fetch the data in a second step after page load. Ajax + rendering on these small devices adds a small delay. On server side with caching on the other side, you're pretty swift.
That said, despite all disadvantages, client side templating has its purpose
Client side templating rules with interactivity and two way data bindings
Typically for RIA (rich internet applications) where you read/edit/browse data in a very interactive fashion, client side templating can be very handy. It becomes a single page app, where the page is stateful and the adequate portions of the page is updated with corresponding data. The downside is of course that such sites are harder to develop, maintain and more error-prone.
For interactive and complex user interfaces it makes sense to leverage the browser for template rendering. However in your case, it's sounds that your page is pretty static, so it boils down to your preference of spending more time coding server-side, or client-side?
Take note that rendering content in the client-side has SEO implications. There are solutions and techniques to overcome this, but make sure you're aware of the effect of dynamically generated content and search-engines.
When rendering on the client-side, if you're requesting the template and the JSON, that's two extra HTTP requests and that will definitely slow down the user experience. However you can preload the template and even the JSON in the initial page-load from the server and make things much faster, for example:
<?php
$data = [ 'title': 'foo', 'content': 'lorem' ];
?>
<script id="tplArticle" type="text/template">
<h1>{{title}}</h1>
<p>{{content}}</p>
</script>
<div id="main"></div>
<script>
var data = <?php echp json_encode($data) ?>
var template = $('#tplArticle').html();
var html = Mustache.to_html(template, data);
$('#main').html(html);
</script>
This is a rough example of a PHP file that outputs the template and JSON on the first page-load from the server, and Javascript rendering the data and template on client-side without any extra HTTP request.
I am admittedly a complete noob in all things server, Linux, and websockets. I finally managed to set up a VM running Apache, Tomcat, and Railo that I could connect to and serve up CFM pages, all the while learning UNIX command line navigation, server theory, etc, etc...
Here's my problem -- there is only one Railo websocket extension and it is super rinky-dink (I had to modify the CFC just to get the service to start) but I can't get a websocket connection up (I keep getting "unexpected code 200" in Google Chrome). There is minimal documentation, which is not helpful at all.
Basically, I am trying to do some prototyping for a future project that will use websockets. I like Railo for its speed, security, and excellent ability for very database heavy operations. I am interested in Node, but don't know how to get the same security and DB functionality out of Javascript as I can with CFML.
So I have a couple questions: what are my best options for WebSocket servers? Should I be trying to use Apache and/or Tomcat? People keep saying it's totally not worthwhile to have something like Node.js running the websockets portion and something else doing the heavy lifting behind it -- why is this? I'm more than happy writing WS handlers in whatever language if I can just get a nudge in the right direction, some excellent tutorials (I can't seem to find much in this department), or good feedback on how to, from the ground up, set up my Linux box to handle websockets -- and preferably how to handle both websockets and a robust language like Railo.
The Railo extension works fine for me.
What about submitting some test code so that we can debug it? Of course the websockets projects is very young and in full deployment. So feel free to fork and submit patches or suggestions.
You have plenty of options:
Railo Google Group
https://groups.google.com/forum/?fromgroups#!forum/railo
Github Extension Repository
submit a but in the Railo Jira bugtracker
The main problem of node.js is that it's mono-thread : you won't be able to do background tasks using it and local IO will block your server.
A solution I use is Go. It's very fast, has very good concurrency features and has integrated websocket and json libraries (sample : http://gary.beagledreams.com/page/go-websocket-chat.html). An efficient web application server is made in a few dozens lines of Go. You'll find that there is still much less documentation on internet than for java or even node.js through.
There are a few implementations of websockets in java but as I'm in the process of switching everything I had in java to Go I hadn't tested them. I know I use Google gson for the json encoding in java and it's very good.
The "unexpected code 200" is caused by Railo's web socket server sending an outdated response. They changed the web socket spec and Chrome uses the newer spec.
The problem seems to be caused by chrome & co implementing the new spec, "draft-ietf-hybi-thewebsocketprotocol-17". It requires the server to respond with "HTTP/1.1 101 Switching Protocols" rather than 200 OK.
The solution here would be to either update the Railo web socket extension yourself or use some other solution:
Here is a complete demo of a web socket chat server written in PHP.
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
I have used this myself to implement a real-time HTML chat served from an Arch Linux machine that I had lying around. Configuration consisted of simply setting up Apache and PHP then changing the IP address in index.html and in server.php to the external ip address of the server machine.
This flynsarmy demo includes a recent version of PHPWebSocket which is an open source web socket server written entirely in PHP and contained in a single file. The demo hooks into three callbacks: connect, message recieved, and disconnect.
The important thing to note, for me, was that the web socket protocol supports text only, not binary so while extending it for my own chat app I had to implement my own commands to help control the server. Commands in my case looked like this:
!kickusers: username, another_username, a_third_username
My server code would check the first character of all messages for a '!' and if present would treat it as a command. Then I slice up the string to get the command "kickusers" and a list of users to kick. Then I call the appropriate kick function and pass it the array of usernames.
Since my scenario was a chat client this meant that the user could literally type this command into chat and the server would accept and respond to it.
The way all this is deployed on my server is like so:
I have Apache serve the index.html page when the user goes to that location on my server in their browser. The only purpose Apache plays here is to give index.html to the client who requested it.
The index.html page contains html to display the chat and javascript to send and recieve chat to/from the server. Basically, index.html is simply a chat client written in HTML and Javascript and it runs in the browser.
I run server.php via ssh on the server to start up the WEB SOCKET server (totally separate from Apache) which just sits there and handles chat stuff like echoing text to the other connected clients etc.
Though the Arch wiki on installing Apache and PHP is specific to Arch in the way that you install the Apache and PHP packages the sections on configuring Apache and PHP apply to all. I'll save you the google query and give you the link here if you like: https://wiki.archlinux.org/index.php/LAMP
As for prototyping, the reason I gave the link to Flynsarmy's chat demo is because his comments are helpful, he wrote a blog about it, and it comes as a very simple yet complete example of how to do something with web sockets in php.
I´ve tried socket.io to create a tiny chat. But now, I´m tring to do the same thing without any dependencies.
My server side seems to be OK, the problem is to render my html page when the browser doesn´t recognize any node.js code, e.g: "require" statement.
The following exception ir raised: Uncaught ReferenceError: require is not defined
I put <script src="chat2.js" type="text/javascript" charset="UTF-8"></script> on my page where "chat2.js" is my server implementation.
I´m rendering the page when I type "localhost:8080" on the webbrowser. I have no idea to makes page recognize the server side code written in the page.
Thanks!
node.js is a server side language. It's designed to run on the server powered by node. What makes this an interesting case is that the server-side language and the client-side language are both JavaScript. In some cases, the same code used on the server-side can also be used on the client side.
For instance, DOM manipulations are examples of actions that can be performed on the server-side, with a document that hasn't been sent to the client, and they're also examples of manipulations that are mostly done on the client-side.
However, you're trying to run code in the browser that can only run on the server. If the code contains modules that have dependencies on the server, then running it in the client is just not possible.