Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Implementing a web sockets client

From: HTML5 Power Workshop

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.

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.

Show transcript

This video is part of

Image for HTML5 Power Workshop
HTML5 Power Workshop

22 video lessons · 3933 viewers

Andy Olsen
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
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.


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 "Already a member? Log in

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

Your file was successfully uploaded.

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.