New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

HTML5 Power Workshop
Illustration by

Implementing a web sockets client


From:

HTML5 Power Workshop

with Andy Olsen

Video: Implementing a web sockets client

In this lesson we're going to see how to implement a web socket client in an HTML page. It'll talk to a web socket server that I've already written implemented using node js. So if you don't already have node js platform installed in your machine all you need to do is to run this MSI file from the Project files folder. And it'll install node js in your Program files folder on windows. And then to actually start the server running, if you open up a command window, and type this in, so it will run the node js engine, and it'll start socketserverws.js.

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
HTML5 Power Workshop
3h 9m Intermediate May 31, 2012

Viewers: in countries Watching now:

In this course, part of his series of titles on HTML5 and CSS3, author and expert Andy Olsen looks at advanced topics like geolocation, mobile development, web sockets, Web SQL, and web workers. You'll also learn how to communicate between pages downloaded from different servers and how to use the new Ajax features in XMLHttpRequest Level 2. After completing this workshop, developers be well equipped to start utilizing the powerful features of HTML5.

Topics include:
  • Using the Communications API
  • Understanding geolocation
  • Getting and watching the current position
  • Using web workers and WebSockets
  • Implementing mobile web user interfaces
  • Managing data in a mobile web application
  • Working offline
  • Using Web SQL
  • Using drag-and-drop
Subjects:
Developer Web Web Design Web Development video2brain
Software:
HTML
Author:
Andy Olsen

Implementing a web sockets client

In this lesson we're going to see how to implement a web socket client in an HTML page. It'll talk to a web socket server that I've already written implemented using node js. So if you don't already have node js platform installed in your machine all you need to do is to run this MSI file from the Project files folder. And it'll install node js in your Program files folder on windows. And then to actually start the server running, if you open up a command window, and type this in, so it will run the node js engine, and it'll start socketserverws.js.

That's the name of my web server, that listens on port 8888 for web socket connections. So the web server is now listening on port 8888 for web socket connections and we're going to make those connections from this client here. Now, the way I've written the server is that it'll only accept web socket connections that are issued from a special domain of local hosts. So, for example, if you tried to run the HTML file directly from the file system, the origin that would get sent over to the server would be null.

And the server would reject that connection so I'll illustrate that now. I'll just press enter. So it didn't connect successfully to the web server. The web server rejected the attempt to connect because the origin wasn't local host. If I go back into the command prompt window, you can see that the web server received the attempted connection from the client. It checked the origin of that request against local host. It wasn't local host, it was actually null. That's what happens when you send requests from a file via the file system.

So to run the client correctly, I'm going to close this window and I'm going to run it, through my local host server, like so. So, this will send, as soon as the webpage starts a connection request for the server to say I am local host, can we have a web socket communication. The web server will accept that request and the client and the server can then communicate asynchronously at the same time. So I'll press enter. So the client has now connected to the server, and the server, as we can see here, accepted the request from local host, and the server is sending back every second a message to the client.

Also, the client can send information back to the server so I can type in here prynhawn da. That means good afternoon in Welsh. It's about 5pm here and a beautiful spring afternoon in South Wales so, good afternoon I'll send that to the server. The server receives that message and bounces back a similar response so here's the message the server receivedFOREIGN and it sent back a response to the client which we can see if I scroll down a bit further, there we go. So, thats the message that the client sent the server and this is the response message that the server sent back to the client.

If I close the client, the server realizes the connection's closed, and it outputs a message of that. So, that's how the example works. Let's see how it's implemented from the client's point of view. So in Commodo edit this is the socket client. The good news is that the API in JAVA script for implementing web sockets is actually quite straightforward. The window object has a websocket property. If your browser supports websockets and that object has an API, which allows you to send messages to the server and to receive messages that get sent back from the server. I have a patch here, if you're running this example on the Firefox Mozilla. In Firefox, the property isn't web socket, the property used instead is called mozilla web socket, like so.

Okay? So this part here is just to make sure that the example will work properly if used in Firefox. Obviously, I was using Chrome, so that isn't exactly relevant in this particular example for me. Right, so when the webpage starts up, this is immediate script. This is the URL that I used to connect to the server. The key point here is well a few key points serve as remnant on local host on 8888, that was the port number. The protocol that you use for websocket communication is WS as opposed to HTTP.

So, as soon as you make a request to a ws protocol, the web server knows that it's attempting to use the elevated web socket protocol as opposed to HTTP. So in HTTP, you have HTTP or HTTPS. For web sockets, you use WS or WSS if you want to have secure communication. So that's the URL of the server that I'd like to have a web socket communication with. What you then do is you create a new web socket object using that URL, okay? So that'll attempt to connect to the web server.

Then there are a series of events that you can handle in your client. So, the on open event will occur when you have a connection that's been opened. I have a log method that I'll show you in a moment which just simply displays messages on the web page. And we invoke this method to send data to the server. So as well as handling events, such as on open, and on close, and on method, you can use this function send to send data from the client to the server whenever you want to.

So, we have an Open Gateway here, the client can send the data to the server whenever it wants, and the server can return data to the client whenever it wants. So, this is full duplex, two-way, asynchronous, bidirectional communication offered by WS. If the server sends data back to the client, then it's handled by the onmessage event. So in that case, this will display messages that are incoming but have been sent from the server back to the browser. And then, when the socket connection is closed, this even occurs, okay? So, let me just scroll down a little further.

I'll show you some of these helper functions. So, in the web page we had the opportunity to type in some text like prynhawn da, and to send that data to the server. So when user clicked the Send button on the web page it calls the do send function. And the do send function gets the text that you've typed in and then sends it to the server using the send function that I was talking about a few moments ago.

And then finally, here, we have a log helper function, which just simply displays messages on the panel in the bump up. So, that's it. That concludes our look at how to implement web socket clients using JavaScript and HTML5. So I'll just summarize the key points. In HTML5, the window object has a web socket property. So you can create a web socket object, specify the URL that you want to connect to and the URL should use the WS or the WSS protocol. You can handle events that indicate the connection has been opened, or the connection has been closed, or that you received data asynchronously from the server.

And if you want to you can send data back to the server by calling the Send function.

There are currently no FAQs about HTML5 Power Workshop.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5 Power Workshop.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.