Description

Chat

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Chat Server</title>
  </head>//from w w w. j  a  v  a 2s  .  c  o m
  <body>
    <div id="chat_wrapper">
      <h2>AwesomeCo Help!</h2>
      <form id="nick_form" action="#" method="post">
        <p>
          <label>Nickname
            <input id="nickname" type="text" value="GuestUser"/>
          </label>
          <input type="submit" value="Change">
        </p>
      </form>
      <div id="chat">connecting....</div>
      <form id="chat_form" action="#" method="post">
        <p>
          <label>Message
            <input id="message" type="text" />
          </label>
          <input type="submit" value="Send">
        </p>
      </form>
    </div>
    <script
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
let setupChat = function(){
 // change this to the IP address of the websocket server
 let webSocket = new WebSocket('ws://192.168.1.2:1234/');
 
 webSocket.onopen = function(event){
   $('#chat').append('<br>Connected to the server');
 };
 
 webSocket.onmessage = function(event){
   $('#chat').append("<br>" + event.data);
   $('#chat').animate({scrollTop: $('#chat').height()}); 
 };
 
 webSocket.onclose = function(event){
   $("#chat").append('<br>Connection closed');
 };

 
  $("form#chat_form").submit(function(e){
    e.preventDefault();
    let textfield = $("#message");
    webSocket.send(textfield.val());
    textfield.val("");
  });

  $("form#nick_form").submit(function(e){
    e.preventDefault();
    let textfield = $("#nickname");
    webSocket.send("/nick " + textfield.val());
  });
};

      
      </script>

  </body>
</html>

Related Topic