kavinder
kavinder

Reputation: 609

Html5 websocket implementation for a java application that can interact with database

I am working on an application that requires a lot of user interaction. Its kind of a discussion form where people can comment. Currently we are using web services and every time user post a comment or a reply to a comment we are calling a webservice and it is communicating with database and doing the rest of the things. I found this process rather slow. So i read in few places that web sockets may be solution to my problem where I can directly use available apis to commiunicate with database and make my application faster. I searched a lot, in some examples available online they were using servlets too and in some they were not. It was very confusing. I just want to use html5 websockets. the UI code is a page which will send some text to backend. The JS code is:

<script>
var connection;



function connect() {
    console.log("connection");
    connection = new WebSocket("not sure what exactly to use here");
    // Log errors 
connection.onerror = function (error) {
  console.log('WebSocket Error ');
  console.log(error);

};

// Log messages from the server 
connection.onmessage = function (e) {
  console.log('Server: ' + e.data); 
  alert("Server said: " + e.data);
};

connection.onopen = function (e) {
console.log("Connection open...");
}

connection.onclose = function (e) {
console.log("Connection closed...");
}
}


function sayHello() {
    connection.send(document.getElementById("msg").value);
}

function close() {
    console.log("Closing...");
    connection.close();
}
</script>

while creating new WebSocket object what path exactly i need to mention. Should I use servlets or not. Please give ideas about the backend java code. Thanks in advance

Upvotes: 0

Views: 940

Answers (1)

Masudul
Masudul

Reputation: 21981

Servlet has not such support. You should use WebSocket of Java EE 7. Your code should be like this

@ServerEndpoint("/echo")
public class EchoEndpoint {
   @OnMessage
   public void onMessage(Session session, String msg) {
      try {
         session.getBasicRemote().sendText(msg);
         //Save message here into database 
      } catch (IOException e) { ... }
   }
}

For Details, see here: http://docs.oracle.com/javaee/7/tutorial/doc/websocket004.htm

Upvotes: 1

Related Questions