-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
358 lines (271 loc) · 19 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<!DOCTYPE html>
<html lang="en">
<head>
<title>Best Tutorial</title>
<link href="style.css" rel='stylesheet'>
</head>
<body>
<div id='entirePage'>
<div id='menu'>
<li class='listNav' id='installMove'><a href='#installPage' class='navItem'>SETUP/INSTALLATION</a></li>
<li class='listNav' id='clientMove'><a href='#clientPage' class='navItem'>CLIENT</a></li>
<li class='listNav' id='serverMove'><a href='#serverPage' class='navItem'>SERVER</a></li>
<li class='listNav' id='gitMove'><a href='#gitPage' class='navItem'>GIT/GITHUB</a></li>
<li class='listNav' id='hostMove'><a href='#hostPage' class='navItem'>HOSTING</a></li>
</div>
<div>
<h4> <a href='#homePage' id='backTop'> ^ </a></h4>
</div>
<div id='homePage' class='page'>
<h1>TOTALLY AWESOME CHAT APPLICATION TUTORIAL</h1>
<h2>One day, four great minds sat down and formulated this tutorial in order to teach the world how to build and awesome chat application using Node.js, JSON, WebSockets, and the like. Please feel free to look through our webpage, and if you like what you see, e-mail us happy thoughts and pictures of cats. If you don't like what you see, still e-mail us happy thoughts and pictures of cats. Thanks and enjoy.</h2>
</div>
<div id='installPage' class='page'>
<h1>Setup and Installation</h1>
<p>For this project you will need NPM, a package manager that runs in the command line and is default for Node.js. Node.js is a server-side platform that is written in Javascript. We will also be utilizing websockets, which allows the client side to communicate with the server side.</p>
<h5>Using NPM and Node in the terminal to install WebSockets (ws):</h5>
<ol>
<li>run "npm init" in order to connect to NPM</li>
<li>Type "node npm install ws --save" and it should install.
<ul>
<li>depending on system preferences, you may need to use the "sudo" command in the terminal.</li>
<li>"ws" is the NPM WebSocket package name. Visit the NPM WebSockets page <a href="https://www.npmjs.com/package/ws" id="wsref" target="_blank">here.</a></li>
<li>"-- save" is used to permanently save the package to your computer. Therefore, you will not need to run "npm install" again.</li>
</ul>
</li>
</ol>
<h5>What are WebSockets?</h5>
<ol>
<li>A WebSocket is an open interactive communication between a user's browser and a server.</li>
<li>They allow for a client to send information to a server, that information gets processed by that server then sent out to a new client. Starting to sound familiar? Maybe like a way to communicate or chat?</li>
<li>This is the package that we will be using in order to create our chat app. Think of this as the foundation. </li>
</ol>
<h5>Setting up HTML/CSS</h5>
<ul>
<li>Before we get knee deep in code we have to set up a bare bones HTML file. The client side will depend on selecting parts of our HTML. If that doesn't make sense, no worries, we will explain more below.</li>
<li>Within the body of your HTML file create three separate DIV elements, you'll want to give them ID's. DIVs should be for a send button, placeholder which will show the client's input, and an area for displaying the text of the conversation.</li>
</ul>
<p>Let's think about this project before we fully delve in. What is a chat app? On the simplest level it is exactly what we explained above with WebSockets. A means for more than one client to connect to each other via a server. We are going to use the "ws" package we installed to build a program that can contain unlimited clients that can connect to a server. We will walk you through, step by step, on how to write both sides. We will even give you some challenges for how to create special functions within your app. Ready to go?</p>
</div>
<div id='clientPage' class='page'>
<h1>Building Your Client.js File</h1>
<p>Double check to make sure all the right packages are installed before you start any actual coding. Revisit the "Setup/Installation" section for more information.</p>
<h5>Declare a host</h5>
<p>First, create a file in your favorite text editor, we recommend naming the file, "client.js". Let's start by declaring a host which will connect us to the server.</p>
<pre><code>
var ws = new WebSocket(server url);
</code></pre>
<p>When you first begin you may want to host your chat app locally. This will allow you to test your code without having to push updated versions to your server or github. That line of code should look a little like this.</p>
<pre><code>
var ws = new WebSocket('ws://localhost:3000');
</code></pre>
<ul>
<li>This will allow you to locally host the chat app.</li>
<li>Being able to host locally is important in order to test out our app.</li>
</ul>
<p>Create an event listener method which will listen for when the page is open or connected to a server.</p>
<pre><code>
ws.addEventListener('open', function(evt){
Almost all of your client code will go inside of here.
});
</code></pre>
<p>In order to set up the basics for your chat app you will need to use DOM manipulation. We already set up a bare bones HTML file. So you will either need to be creating new elements through DOM manipulation or selecting them. For example to target the submit button in your html you may write something similar to the following:</p>
<pre><code>
var submitButton = document.querySelector('button');
</pre></code>
<p>What information are you storing about your client? We will be using OBJECTS to store multiple key/value pairs (hashes). Lets keep it simple and just transfer a name and text between users.</p>
<pre><code>
var object = {
name : name,
text : YourInputBox.value,
}
</pre></code>
<ul>
<li>".value" is a property used when sending data to the server, it returns the value of the data in the form of a string.</li>
</ul>
<p>Wait, we can't send Objects the way they are formatted. So how do we send information? JSON. JSON (JavaScript Object Notation) is just a simple way to interchange data. Since clients can only send data in the form of strings, JSON is able to break code down and represent it in the form of objects with key/value pairs, hashes or arrays. There are two main commands for the sending and receiving data through JSON:</p>
<ul>
<li>Stringify - sending data</li>
<ul>
<li>The stringify method alters objects into strings so that data can be transmitted and received. Again, clients can only send data in the form of strings that can be read by the server. </li>
<li>Once an object has been stringified it can be sent by the client to the server using ws.send (more on that later).</li>
</ul>
<li>Parse - receiving data</li>
<ul>
<li>The server has not received stringified data from the client, but now we need to send that data out to the next client as an object.</li>
<li>We use the parse method to turn our string back into an object and send it out.</li>
<li>And once the client receives the data, the whole process of stringify and parse starts over again.</li>
</ul>
</ul>
<pre><code>
var stringified = JSON.stringify(object);
var parsed = JSON.parse(object);
</pre></code>
<h5>Sending Information</h5>
<ol>
<li>Create an event listener which will listen for an action. For example, clicking the submit button.</li>
<li>When this event is triggered it will run a function which should include a "send" method.</li>
<li>In this case, userMessage, will be a stringified object.</li>
<li>The values within the object are text which was grabbed from an input box (which we created in our HTML) the moment the submit button was clicked.</li>
<li>What does this mean? This about the first step of writing in a chat app. We open our app, type into and input box, and click send. </li>
</ol>
<pre><code>
button.addEventListener('click', function(){
var object = {
name : name,
text : YourInputBox.value,
}
var userMessage = JSON.stringify(object);
ws.send(userMessage);
});
</pre></code>
<h5>Receiving Information</h5>
<ol>
<li>The event listener in this scenario will be "message."" Whenever a message is received by the client, the file will run a function.</li>
<li>The goal is to use stringify and parse in both the client and server JS files. For example, the server should be parsing and storing some of the information which has been sent, such as keeping a history of the chat, to share with new users. The server would then stringify and send the information back out to the new clients. </li>
<li>Receiving messages will always need to be parsed for the server to be able to read them. Once parsed you can determine what to do with the values in the object:</li>
</ol>
<pre><code>
ws.addEventListener('message', function(x){
var parsed = JSON.parse(x.data);
var paragraph = document.createElement('span');
var userbubble = document.createElement('div');
var lineBreak = document.createElement('br');
paragraph.innerText = parsed.name + ": " + parsed.text;
paragraph.appendChild(lineBreak);
userbubble.appendChild(paragraph);
ChatBoxDiv.appendChild(bubble);
});
</pre></code>
</div>
<div id='serverPage' class='page'>
<h1>Building Your Server.js File</h1>
<p>Now that we have a super fancy functional client, we need a server so we can actually run our app. Remember all messages need to be sent through a server. Without this we have nothing. Let's begin by creating and opening a server.js file. We need to first declare a WebSocket server object using the same ws package. We are declaring the variable for the actual server: </p>
<pre><code>
var WebSocketServer = require("ws").Server;
var server = new WebSocketServer({port : 3000});
</pre></code>
<p>Port:3000 is simply telling the server which port to listen on. This is important for when we get to the hosting stage.</p>
<p>The server will need to maintain a list of all connected clients. Let's go ahead and create a new variable called clients. This will be an empty array. </p>
<pre><code>
var clients = [];
</pre></code>
<p>We need an event listener for the event of each client connecting to the server. This is what it's all about; it's basically what the server is for. All the other code will go inside this event listener.</p>
<pre><code>
server.on('connection', function(ws){
})
</pre></code>
<p>While the WebSocket connection is running, we want to perform three tasks: (1) add the new client to the server-maintained clients array, (2) listen for a WebSocket connection closing, and (3) listen for a message from a WebSocket client and broadcast it.</p>
<ol>
<li>Add the new client to the server-maintained clients array.</li>
<pre><code>
server.on("connection", function(ws) {
clients.push(ws);
</code></pre>
<li>Listen for a WebSocket connection closing. Close it and remove it from the array. This is important. Without this step, every time a client leaves, our app will crash.</li>
<pre><code>
server.on("connection", function(ws) {
clients.push(ws);
ws.on("close", function() {
var x = clients.indexOf(ws);
clients.splice(x,1);
console.log("Clients connected: " + clients.length);
})
});
</code></pre>
<li>Listen for a message from a WebSocket client and broadcast it.</li>
<pre><code>
ws.on("message", function(input) {
</code></pre>
</ol>
<ul>
<li>As mentioned above, we need to use JSON to parse the input, translating it from a string to an object.</li>
<pre><code>
processedInput = JSON.parse(input);
console.log(processedInput.name + " : " + processedInput.text);
</code></pre>
<li>Finally, we loop through each client in the array and send out the message to each of them.</li>
<pre><code>
for (i = 0; i < clients.length; i++) {
clients[i].send(input);
</code></pre>
<li>Eveything together looks like this:</li>
<pre><code>
server.on("connection", function(ws) {
clients.push(ws);
ws.on("close", function() {
var x = clients.indexOf(ws);
clients.splice(x,1);
console.log("Clients connected: " + clients.length);
});
ws.on("message", function(input) {
processedInput = JSON.parse(input);
console.log(processedInput.name + " : " + processedInput.text);
for (i = 0; i < clients.length; i++) {
clients[i].send(input);
}
});
</code></pre>
</ul>
</div>
<div id='gitPage' class='page'>
<h1>What is Git and Github?</h1>
<p>Git is a VCS (Version Control System). Simply put, it's a timeline for your project but a better way to understand it is like a tree. Your tree works like any other - with a base (master) and branches. With each project you will create a new repository (a project folder) and will be adding, committing, and pushing to that repo. Adding and committing are actions that happen locally (on your computer) but in order to fully save them you need to push everything to GitHub. <a href="https://github.com" target="_blank">GitHub</a> is a website where you are saving all these different stages of your code. You can head over and view your code and so can others. Being able to save in stages is important because we all mess up sometimes. You'll want to be able to go back in time to before the mess up occurred. When this happens - you'll be using <code>clone</code> and <code>pull</code>. Branches are cool because they allow you to keep working on your project but in a separate place. Let's say you want to add some features but aren't completely confident in the process. Branch off of master (the base) and work away. If the code is a success, you can always <code>merge</code> that branch to master later.</p>
<h5>Let's break the process down:</h5>
<ol>
<li>Head over to <a href='www.github.com'>www.github.com</a> and sign up or log in.</li>
<li>Once you're all logged in, head over to the top right corner, hit the "+" icon, and select "Create New Repository".</li>
<li>You have a choice to make this file private or public. You should be making it public.
Why make a public repo? This way anyone can access your code! Employers often want to check out good code in GitHub so you'll want to be able to share this. There's a lot of cool projects that made it big. Who knows? Maybe your chat app will get noticed. </li>
<li>Once you've created your new repo you will be taken to an empty project page. Once you have pushed to GitHub, all your files can be accessed here.</li>
</ol>
<h5>Committing to Github</h5>
<ol>
<li>Open terminal and make sure you are in your projects folder (directory).</li>
<li>Type <code>git init</code>. This will get GIT running. </li>
<li>Type <code>git add .</code> in order to add all the files in the directory. You don't have to add everything at once, but this is a great shortcut. </li>
<li>To make the actual commit you will need to type <code>git commit -m </code><i>[some sort of message]</i>. What is committing and how is it different then adding? When you added your files all you did was add them, nothing was really saved. Committing is going to actually save all those files to be accessed later. Remember, nothing is on GitHub yet - this is still only local. Messages are important so that you remember exactly what occurred. Be careful with what words are used in messages, sometimes employers like to check them out. </li>
<li>We need to give our saved files a place to go. Head back to GitHub and copy the SSH link. It will look something like this: <code>[email protected]:JohnSmith/chatapp.git</code>.</li>
<li>In terminal type out <code>git remote add origin [email protected]:JohnSmith/chatapp.git</code>.</li>
<li>Last step—<code>git push origin master</code> and you should get some sort of message when this process is completed.</li>
<li>Refresh the project page and all your files, folders, and code should be there.
What exactly is happening here? We are saving our commit to GitHub and telling it that our origin is our base (master). If you were working off a branch you would type that branch name instead of master.</li>
</ol>
</div>
<div id='hostPage' class='page'>
<h1>Hosting Your Awesome Project on Digital Ocean</h1>
<p>Digital Ocean(DO) is a server service where you will be able to host your project. The following three items are necessary before starting the hosting steps:</p>
<ol>
<li>Create a <a href="http://www.digitalocean.com" target="_blank">Digital Ocean Account</a></li>
<li>Grab the SSH key from the Github repository that contains your chat application. This will connect your javascript server to the DO server. The SSH key can be found on the right hand side of the repo page underneath settings.</li>
<li>Finalize your files before pushing to the Github repository. Put all of your files in a single folder, and make sure that folder includes the JSON and WS packages. If it does not, "cd" into that folder on your terminal screen and run the commands "npm init" and "npm install ws --save." Make sure your client.js file is requesting to connect to your digital ocean url, and not to a local host. Now push to the Github repo.</li>
</ol>
<pre><code>
var ws = new WebSocket('ws://jason.princesspeach.nyc:3000');
NOT
var ws = new WebSocket('ws://localhost:3000');
</pre></code>
<h5>Hosting Steps</h5>
<ol>
<li>In your terminal SSH to your DO box by running, "ssh root@yourDOurlname". You should now be inside the DO box on this terminal window</li>
<li>from here run the following command to link to the chat app repo on your Github. "git clone yourrepohttpslink". By doing this, you will be able to use the "git pull origin master" command any time you make a change to the original Github repo. </li>
<li>"cd" into the repo folder and run "npm install"</li>
<li>Run your chat app's server code by using the "node serverfilename" command. This will turn your DO box into a websocket.</li>
<li>Open another terminal window without closing your current one.</li>
<li>In the new terminal window SSH to DO and "cd" into the app folder.</li>
<li>run "http-server". This will turn your DO box into a server running the html and css files that are in the folder.</li>
<ul>
<li>By only running "http-server" any connecting users will have to add the port number to the end of the url. For example: "http://yourDOname:8080</li>
<li>If you run "http-server -p80" users will be able to connect by using the url without typing in "8080"</li>
</ul>
</ol>
</div>
<div id='lastPage' class='page'>
<h1 id='congrats'>Congratulations On Your Victory!</h1>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script src='tutorial.js'></script>
</body>
</html>