Creating a Web Socket application

A simple application with chat room type functionality, where a user may read the current list of messages, as well as add their own message to the room.

A html page with text entry box where new messages are written before being sent, and we’ll have a list of messages in the chat room.It is a simple chat room message sending and receiving.

snippet
<!DOCTYPE html>
<html>

<head>
<title>Our Chatroom</title>
<script src="chatroom.js"></script>
</head>

<body>
<h1>Our Chatroom</h1>
<div id="chatlog"></div>
<input id="newmsg" />
<br />
<input type="button" value="Send Message" id="sendmsg" />
</body>

</html>

JavaScript in "chatroom.js":

snippet
var chatcomm = new WebSocket("ws://something.com/server/chat");
chatcomm.onmessage = function(msg) {
msg = JSON.parse(msg); // decode JSON into object
var chatlog = document.getElementById("chatlog");
var docfrag = document.createDocumentFragment();
var msgdiv;
for (var i = 0; i < msg.messages.length; i++) {
msgdiv = document.createElement("div");
msgdiv.appendChild(document.createTextNode(msg.messages[i]));
docfrag.appendChild(msgdiv);
}
chatlog.appendChild(docfrag);
};
chatcomm.onclose = function() {
alert("The chatroom connection was lost. Refresh page to reconnect.");
};
document.getElementById("sendmsg").addEventListener("click", function() {
var newmsg = document.getElementById("newmsg");
chatcomm.send(newmsg.value); // send the message to the server
newmsg.value = ""; // clear out the message entry box
}, false);

Create the socket and point it at a location on our server. The server URL in our example uses the "ws://" protocol. This specifies the special protocol that Web Sockets use between client and server.

Adding Event Listeners
Set up two event listeners on our socket object: onmessage and onclose. The onclose handler is self-explanatory—it is fired when the connection is closed.

The onmessage handler receives a string of data (JSON), and parses it into a message object. The message object has an array of one or more messages (each one is just simple text). The handler loops through each message, adding it to the chat log in the order received.

Lastly, Sets up a click event handler on the "Send Message" button. When clicked, the handler takes whatever has been typed into the entry input, and sends it to the server, using the send(...) method.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +