Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 19 January 2013

WebSocket with Java (Simple HelloWorld ChatApp using websocket and atmosphere in java)

Hello all ! Today i am going to introduce and share my knowledge and findings on 'How to integrate Websocket in Java'.
Here we w'll start with a simple chat app using websocket and java. Before we start make sure that your browser and server supports websocket. In this example i am using two well known browsers and a server that supports Websockets.
Firefox Setup 17.0.1
Google.Chrome (latest version)
apache-tomcat-7.0.30
First of all let's look at the application structure to better understand the sample application.


Now let me show you all library files that i have used to make it working , please add those files in your lib folder before you start.


Now lets start adding all required files one by one to our project structure .
src\com\javaguys\help\Message.java
package com.javaguys.help;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement

public class Message {

 public String author = "";

 public String message = "";

 public Message() {

 }

 public Message(String author, String message) {

  this.author = author;

  this.message = message;

 }

}

src\com\javaguys\help\ResourceChat.java
package com.javaguys.help;

import org.atmosphere.annotation.Broadcast;

import org.atmosphere.annotation.Suspend;

import javax.ws.rs.Consumes;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

@Path("/")

public class ResourceChat {

 @Suspend(contentType = "application/json")

 @GET

 public String suspend() {

  return "";

 }

 @Broadcast(writeEntity = false)

 @POST

 @Produces("application/json")

 public Response broadcast(Message message) {

  return new Response(message.author, message.message);

 }

}

src\com\javaguys\help\Response.java
package com.javaguys.help;

import javax.xml.bind.annotation.XmlRootElement;

import java.util.Date;

@XmlRootElement

public class Response {

 public String text;

 public String author;

 public long time;

 public Response(String author, String text) {

  this.author = author;

  this.text = text;

  this.time = new Date().getTime();

 }

 public Response() {

 }

}
now we are done with adding server side code , lets add some actual stuff that w'll relate to the client side and application.

WebContent\css\style.css
* {

 font-size: 14px;

 padding: 0px;

 margin: 0px;

}

p {

 line-height: 18px;

}

div {

 width: 1000px;

 margin-left: auto;

 margin-right: auto;

}

#content {

 font-family: tahoma;

 padding: 5px;

 background: #ddd;

 border-radius: 5px;

 border: 1px solid #CCC;

 margin-top: 10px;

 font-size: 14px;

}

#header {

 text-align: center;

 font-family: Segoe Print;

 padding: 5px;

 background: teal;

 border-radius: 5px;

 border: 1px solid #CCC;

 margin-top: 10px;

 color: white;

}

#input {

 border-radius: 2px;

 border: 2px solid #ccc;

 margin-top: 10px;

 padding: 5px;

 width: 890px;

}

#status {

 width: 88px;

 display: block;

 float: left;

 margin-top: 15px;

 font-size: 14px;

}

WebContent\jquery\application.js
$(function() {

 "use strict";

 var content = $('#content');

 var input = $('#input');

 var status = $('#status');

 var myName = false;

 var author = null;

 var logged = false;

 var socket = $.atmosphere;

 var request = {

  url : document.location.toString() + 'chat',

  contentType : "application/json",

  logLevel : 'debug',

  transport : 'sse',

  fallbackTransport : 'long-polling'

 };

 request.onOpen = function(response) {

  content.html($('<p>', {

   text : 'Application connected using ' + response.transport

  }));

  input.removeAttr('disabled').focus();

  status.text('Choose name:');

 };

 request.onMessage = function(response) {

  var message = response.responseBody;

  try {

   var json = jQuery.parseJSON(message);

  } catch (e) {

   console.log('This doesn\'t look like a valid JSON: ', message.data);

   return;

  }

  if (!logged) {

   logged = true;

   status.text(myName + ': ').css('color', 'blue');

   input.removeAttr('disabled').focus();

  } else {

   input.removeAttr('disabled');

   var me = json.author == author;

   var date = typeof (json.time) == 'string' ? parseInt(json.time)

     : json.time;

   addMessage(json.author, json.text, me ? 'blue' : 'black', new Date(

     date));

  }

 };

 request.onClose = function(response) {

  logged = false;

 }

 request.onError = function(response) {

  content.html($('<p>', {

   text : 'Sorry, but there\'s some problem with your '

     + 'socket or the server is down'

  }));

 };

 var subSocket = socket.subscribe(request);

 input.keydown(function(e) {

  if (e.keyCode === 13) {

   var msg = $(this).val();



   // First message is always the author's name

   if (author == null) {

    author = msg;

   }

   subSocket.push(jQuery.stringifyJSON({

    author : author,

    message : msg

   }));

   $(this).val('');



   input.attr('disabled', 'disabled');

   if (myName === false) {

    myName = msg;

   }

  }

 });

 function addMessage(author, message, color, datetime) {

  content.append('<p><span style="color:'

    + color

    + '">'

    + author

    + '</span> @ '

    + +(datetime.getHours() < 10 ? '0' + datetime.getHours()

      : datetime.getHours())

    + ':'

    + (datetime.getMinutes() < 10 ? '0' + datetime.getMinutes()

      : datetime.getMinutes()) + ': ' + message + '</p>');

 }

});

we have two more js files to add up here , because of more number of lines i am not able to paste the code here.
WebContent\jquery\jquery.atmosphere.js WebContent\jquery\jquery-1.7.2.js
these two are well known js files and can be downloaded from internet . please add these two files at related place. if you are not able to find these files please mail me , i w'll send you the files asap.
WebContent\WEB-INF\web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"

 xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


 <description>Oodles Chat App</description>

 <display-name>Oodles Chat App</display-name>

 <servlet>

  <description>AtmosphereServlet</description>

  <servlet-name>AtmosphereServlet</servlet-name>

  <servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>

  <init-param>

   <param-name>com.sun.jersey.config.property.packages</param-name>

   <param-value>com.javaguys.help</param-value>

  </init-param>

  <load-on-startup>0</load-on-startup>

 </servlet>

 <servlet-mapping>

  <servlet-name>AtmosphereServlet</servlet-name>

  <url-pattern>/chat/*</url-pattern>

 </servlet-mapping>

</web-app>

WebContent\index.html
<!DOCTYPE html>

<script type="text/javascript" src="jquery/jquery-1.7.2.js"></script>

<script type="text/javascript" src="jquery/jquery.atmosphere.js"></script>

<script type="text/javascript" src="jquery/application.js"></script>

<link rel="stylesheet" type="text/css" href="css/style.css">

<html>

<head>

<meta charset="utf-8">

<title>Java Guys | Simple Chat App</title>

</head>

<body>

 <div id="header">

  <h3>Java Guys | Simple Chat App using Websocket !</h3>

 </div>

 <div id="content"></div>

 <div>

  <span id="status">Wait! Connecting...</span> <input type="text"

   id="input" disabled="disabled" />

 </div>

 <div id="header">

  <span><h3>Happy Coding !</h3> </span> <span></span>

 </div>

</body>

</html>

Now we are all done with adding all files to app, now start your server and if your server and browsers support websocket you w'll see something like these screens.

web-socket-atmosphere-in-java

websocket-atmosphere-in-java

websocket-atmosphere-in-java

as you can see, we can assume these two browsers as two client and we are able to see quick response server without being requested by the client. That's all about implementing reverse ajax and server push using atmosphere and websocket.









Thanks for reading !
Being Java Guys Team



52 comments:

  1. it is running only html page......further not working..can u tell steps

    ReplyDelete
  2. also tell me pre-requisites?

    ReplyDelete
    Replies
    1. hi,

      Sorry for late reply, can you please tell me your email address so that i could send you sample project and other details.

      Thanks

      Delete
  3. Plz tell me 4m where I got these jar files which you added above in lib

    ReplyDelete
  4. Hi, finding these jars is very easy just do a google search for them.

    Thanks

    ReplyDelete
  5. My email is sunlightasia@gmail.com. Please send me a sample of this tut which can run on eclipse or tomcat. Thank you.

    ReplyDelete
  6. Thanks your post..
    Please send me a pre-requisites about this project..all a step to do this project..i am a newbie in web java socket..so please help me..
    my email is delboeaz@yahoo.co.id..

    many thanks..

    ReplyDelete
  7. hi Ankush Thakur, can you send me your sample project and other detail. because when i try, it's doesn't work
    this my email patrajasasibuea@gmail.com

    ReplyDelete
  8. Hi please tell me i am getting only html page with wait display...
    can you please tell me how it will work
    dnyaneshwar.jadhav1@gmail.com

    ReplyDelete
  9. Hi,

    i am getting only html page with wait display...
    can you please send me the project?
    snabelkabiya@gmail.com

    Thanks,

    ReplyDelete
  10. Hi can you send me the whole project for this tutorial.. jeson_enerez@yahoo.com

    ReplyDelete
  11. Hi,
    could you please send me the complete project for this tutorial on jitendra_pawa@yahoo.co.in. Many Thanks!!!

    ReplyDelete
  12. Hi could you send me the tut please?
    rashid.alriyami89@gmail.com

    ReplyDelete
  13. Hi could you send me the project please, great help
    jayjay0109@gmail.com

    ReplyDelete
  14. Hi can you please send me this sample project to my mail ranjith1882@gmail.com

    ReplyDelete
  15. Hi, please can you send me the code for the project my email is orion_pax666@hotmail.com

    ReplyDelete
  16. Please send me complete project of this tutorial which can run on eclipse. Thank you. My email is jaydip10@gmail.com

    ReplyDelete
  17. Please send me complete project of this tutorial which can run on eclipse. Thank you. My email is harishjonah@gmail.com

    ReplyDelete
  18. this not working plz send full project on my mail id srsingh784@gmail.com

    ReplyDelete
  19. Could you please send me a project for this tutorial? My email is lightning360@gmail.com
    Thank you in advance

    ReplyDelete
  20. Hi, can you please send me the code for the project, i tried but its not working... my email id is vennapusa.suneetha@gmail.com

    ReplyDelete
  21. Hi,

    I am developing web based application. In that application I need to use chat functionality. e.g If 10 users are login in to that application they can chat internally. i am using jsp and servlet technology. can some one please help me for what i need to do?

    ReplyDelete
  22. Hi..
    can you please send me the code I tried bt its not working

    ReplyDelete
  23. my mail id is :swati.joshi750@gmail.com


    Thanks

    ReplyDelete
  24. Can you please send the project coding at
    nileshvid@gmail.com

    ReplyDelete
  25. Can you please send the project code to tn.pradeep@gmail.com

    ReplyDelete
  26. pls send me the full working code for this on my email dppurohit90@gmail.com....its urgent...plssss

    ReplyDelete
  27. pls send me full code on my email: ldmtam@outlook.com . thanks so much :))

    ReplyDelete
  28. kindly send this sample to my mail id vkarhtiit@gmail.com.some of the thinks not working properly

    ReplyDelete
  29. Please send your project at
    svk_ry@yahoo.com
    Thank You.

    ReplyDelete
  30. Please would you be so kind to send me the project? whitepony378@gmail.com thank you so much

    ReplyDelete
  31. This is jst a waiting page display.
    pls send me the full code that working in this email id
    dppurohit90@gmail.com..
    pls
    thanks

    ReplyDelete
  32. hi ankush, can u plz send me ur sample project on my email id:attarde.yogesh08@gmail.com

    ReplyDelete
  33. i am getting only html page with wait display...
    can you please send me the project?
    p.2shukla@gmail.com

    ReplyDelete
  34. Can you send me the sample project with prerequisites on my mail id vattikuti.ramabrahmam@gmail.com



    Thanks,
    Rama

    ReplyDelete
  35. can you please send me the sample projects at cece.marela@gmail.com

    ReplyDelete
  36. Hi Ankush,

    I also tried this project but its now running. I think the problem is in URL section of req var. When I tried to print the URL its :- "http://localhost:8080/MyApp/index.htmlchat"

    Can u correct me where I am wrong.

    Thanx in advance.

    ReplyDelete
  37. Hi ! can you please send me the sample projects at vantrung126@gmail.com

    ReplyDelete
  38. Can you send me the sample project with prerequisites on my mail id linhvv@gmail.com

    Thanks!!!

    ReplyDelete
  39. This project is working fine. I have deployed this on server. This is good for chat application using socket. For any assistance , You can mail on bijendrachauhan100@yahoo.co.in

    ReplyDelete
  40. Hi ! can you please send me the sample projects at sachindv354@gmail.com

    ReplyDelete
  41. Hi Sir I tried but I get only html page with waiting...please help me I am very thankful to your code..this is my mail id:mahender867@gmail.com.
    thanks in advance.

    ReplyDelete
  42. Hi,
    I got the same problem. Compiled and running successfully but I get 'wait connecting' and the text is disabled. Please assist.
    Moshe

    ReplyDelete
  43. Hi,
    I'm also getting same message as "Wait Connecting"
    my email is vittalisvital@live.com
    assist me please

    ReplyDelete
  44. can you send me the project : a.ennajmaoui@gmail.com , thanks

    ReplyDelete
  45. please send me the project sunil.8286052949@gmail.com

    ReplyDelete
  46. can you please send complete project my email srinivas.pjava@gmail.com
    thanks.

    ReplyDelete
  47. Im also interested in the project. If you could mail me to uo180258@uniovi.es

    Thanks a lot

    ReplyDelete
  48. @Ankush Please send me this complete project and its details as I have to implement it into my Spring MVC application. My email is:
    zia_ul_mustafa@hotmail.com

    Waiting for your reply. Thanks in advance.

    ReplyDelete
  49. Giddaluri Madhavi23 July 2015 at 00:29

    Thnx 4 the info.
    will u plz mail me this project. i tried it to build with maven on eclipse Ide. it's not working.. i don't know where am i going wrong.


    Can u help me with this.

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft