Logo  

CS479/579 - Web Programming II

Displaying ./code/Web-sockets/chat.html

<!DOCTYPE html>
<html>
<head>
 <title> </title>
 <meta charset='utf-8'>
 <style>
 #chatwin { min-width: 90%; }
 #chatlog {
  border: 1px solid black;
  overflow-y: scroll;
  height: 480px;
 }
 input[type=text] {
   min-width: 100%;
   border: 1px solid gray;
   font-size: 20pt;
   border-radius: 4px;
 }
 </style>
 <script>
 // The users saved name and the connection object:
 var _name = null, _conn = null;

 /**
  * Called after a name is entered. Establishes the web-socket connection and
  * setups the onmessage event listener which adds received messages to the
  * chatwin.
  */
 function setup(e) {
   console.log("setup: %s", e.value);
   _name = e.value;
   e.value = "";
   document.getElementById("name").setAttribute("style", "display:none;");
   document.getElementById("chatwin").setAttribute("style", "display:table;");
   _conn = new WebSocket("ws://vid.indstate.edu:60000/", "test");
   _conn.onmessage = function(em) {
     var data = JSON.parse(em.data);
     var l = document.getElementById("chatlog");
     l.innerHTML += "<strong>" + data.name + "</strong>: " + data.message + "\n";
   }
 }

 function send(e) {
   _conn.send(JSON.stringify({name: _name, message: e.value}));
   e.value = "";
 }
 </script>
</head>
<body>
<!--
  The chatwin table is not visible initially. The Name input is removed after
  a name is entered and the chatwin is made visible.
-->
<label id='name'> Name: <input type='text' onchange='setup(this);'></label>
<table id='chatwin' style='display:none;'>
 <tr><td><pre id='chatlog'></pre></td></tr>
 <tr><td><input type='text' onchange='send(this);'></td></tr>
</table>
</body>
</html>