Practice exercises CHAPTER 10 425
- You want to ensure that the WebSocket connection is not disconnected as a result of
inactivity. How can you accomplish this?
A. Add code to the onclose event to reopen the connection when it’s closed.
B. Add code to send an empty message periodically before the connection is closed.
C. Set the keepAlive property on the WebSocket object to true.
D. Create a new WebSocket object each time you send a message.
Practice exercises
If you encounter a problem completing any of these exercises, the completed projects can be
installed from the Practice Exercises folder that is provided with the companion content.
Exercise 1: Create a chat server
In this exercise, you apply your WebSocket knowledge by creating a chat server web applica-
tion. Although you won’t use the WebSocket object directly, you will use the Socket.IO library,
which provides a WebSocket wrapper that simplifies client and server communications.
In this exercise, you create the chat server. You won’t be able to test this server effectively
until you complete Exercise 2, in which you create the HTML page.
- If you haven’t done so yet, install Node.js from http://nodejs.org/.
- Open the command prompt window.
- Create a folder for the new website.
You must navigate to the location and then create the folder. For example, the follow-
ing commands navigate to the node_samples folder on the root of the C drive, create a
new chat_service folder, and then navigate to the new folder.
C:
cd \node_samples
md chat_service
cd chat_service - In the chat_service folder, create a package.json file by typing the following command.
npm init
This command starts the wizard. Enter the following. (Press Enter to accept default
values for fields not shown.)
■■Name: chat_service
■■Version: 0.0.0
■■Description: A simple chat service
■■Entry Point: app.js