The first thing we will do is establish a connection with our signaling server. The signaling server that we built in Chapter 4, Creating a Signaling Server, is entirely based on the WebSocket protocol. The great thing about the technology that we built on top of is that it requires no extra libraries to connect to the server. It simply uses the built-in power of WebSocket in most up-to-date browsers today. We can just create a WebSocket object directly, and connect to our server in no time at all.
We can start by creating the client.js file that our HTML page includes. You can add the following connection code:
var name, connectedUser; var connection = new WebSocket('ws://localhost:8888'), connection.onopen = function () { console.log("Connected"); }; // Handle all messages through this callback connection.onmessage = function (message) { console.log("Got message", message.data); var data = JSON.parse(message.data); switch(data.type) { case "login": onLogin(data.success); break; case "offer": onOffer(data.offer, data.name); break; case "answer": onAnswer(data.answer); break; case "candidate": onCandidate(data.candidate); break; case "leave": onLeave(); break; default: break; } }; connection.onerror = function (err) { console.log("Got error", err); }; // Alias for sending messages in JSON format function send(message) { if (connectedUser) { message.name = connectedUser; } connection.send(JSON.stringify(message)); };
The initial thing we do is set up the connection to our server. We do this by passing in the location of our server, including the ws://
protocol prefix on our URI. Next, we set up a series of event handlers. The main one to take note of is the onmessage
handler, which is where we will get all of our WebRTC-based messages. The switch
method calls different functions based on the message type, which we will fill out later in this chapter. Finally, we create a simple send
method, which will automatically attach the other user's ID to our messages and encode them for us. We also set up some variables to hold your username and the other user's ID for later use. When you open this file now, you should see a simple connection message:
The WebSocket API is a solid foundation for building real-time applications. As you will see from this chapter, it enables us to send back and forth information between the browser and the server almost instantly. Not only can we use this for signaling data, but also other information as well. WebSockets has been used in a number of different websites, such as multiplayer gaming, stock brokering, and more.
18.218.168.16