HTML and CSS Reference
In-Depth Information
To test if the browser supports Web Sockets, use the following feature-detect for the
WebSocket API:
var websockets_support = !!window.WebSocket;
Now, let's build a simple application with chat room-type functionality, where a user
may read the current list of messages and add her own message to the room.
We'll have a text entry box where new messages are written before being sent, and we'll
have a list of messages in the chat room. We don't need features such as login or au-
thentication here, only simple chat room message sending and receiving:
<!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>
Now, let's examine the JavaScript in chatroom.js :
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
 
Search WWH ::




Custom Search