Thursday, June 26, 2014

What are Websockets


Websockets allow two way communication between the server and the Client resulting low latency communication between client and the server. It allows  full-duplex communications channels over a single TCP connection. It also allows to break free from the request/response paradigm on what the traditional web was based on. Websockets further enhances the AJAX capabilities, where AJAX communication is also steered by a Client.

WebSockets provide new protocol between client and server which runs over a persistent TCP connection. Through this open connection, bi-directional, full-duplex messages can be sent between the single TCP socket connection (simultaneously or back and forth).


WebSockets Diagram How do websockets work?


The sample

The Sample demonstrate a simple application that runs with web-sockets, the application will echo/ broadcast messages when the server receives it to all the active connections.

GlassFish server will be used with eclipse IDE to develop the sample.

How to Create the Application

Writing The Socket Server

Step 01

Open Eclipse and Create a new dynamic web project with the name "webSocketSample" and with all the default configurations.



Step 02

Add the Glassfish server to your Project, This can be done in many ways the easiest way is to first download the compatible version of GlassFish server and then add it. You can do this by Going to Servers Tab and Select Add new server as shown below.



Follow the wizard and make sure you add your project to configured project list so it will automatically get deployed when the server in starting.


Step 03

Expand the project and go to Javaresorces/src  directory and create a new Java class with the following Name and package.



Note : Make sure You have added all the Libraries to your Project as shown below. (The Glassfish System library contains some jars needed for this project) If not added you can these libraries manually.





Step 03

Add the following Code Snippets to your newly Created Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package org.socket.server;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.*;

@ServerEndpoint("/server")
public class SocketServer { 
 
 // Storing the sessions
 static Set <Session> clientUIs = Collections.synchronizedSet(new HashSet<Session>());
 @OnOpen
 public void handleOpened(Session clientSession) throws IOException {
  clientUIs.add(clientSession);
  
   clientSession.getBasicRemote().sendText(buildJsonData("System", "You are now connected to the Map Server!!!"));
 
  System.out.println("A New Client is Connected!!!!");
 }
 
 @OnMessage
 public void handleMessage(String message, Session clientSession) throws IOException{
   System.out.println("A Message Received!!!");
     
   Iterator<Session> iterator = clientUIs.iterator();
   while (iterator.hasNext()){
    
    iterator.next().getBasicRemote().sendText(buildJsonData("Message : ", message));
    
   }
 }
 
 @OnClose
 public void handleClose (Session id){
  
  clientUIs.remove(id);
 }

 private String buildJsonData(String id, String message) {
  // TODO Auto-generated method stub
  JsonObject json = Json.createObjectBuilder().add("message", id+ ": " +message).build();
  StringWriter strwriter = new StringWriter();
 
   try (JsonWriter jsonwriter = Json.createWriter(strwriter)) {jsonwriter.write(json);}
  
   System.out.println("The Jason : "+strwriter.toString());
  return strwriter.toString();
 }

}



Writing The Client To Access the Socket

Step 01

Now in your project go to webcontent  directory and create a file called "index.html"

And add the following code into that file. Note the Javascript code that initiate the websocket connection.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Map UI</title>
<script type="text/javascript">
 var websocket = new WebSocket(
   "ws://localhost:8080/webSocketSample/server");

 websocket.onmessage = function processMessage(message) {

  var jsonData = JSON.parse(message.data);
  if (jsonData != null) {
   messagesTextArea.value += jsonData.message + "\n";

  }
 }
 function sendMessage() {
  websocket.send(messageText.value);
  messageText.value = "";

 }
</script>
</head>
<body>

 <div>
  <br>
  <br>
  
  <h3>Output Console</h3>
    
  <textarea id="messagesTextArea" rows="8" cols="80"></textarea>
  <br>
  <input type="text" id="messageText" size="50" /> 
  <input id="button1" type="button" value="Send Message" onclick="sendMessage();">

 </div>


</body>
</html>


Step 02

Make sure that you don't have any errors in the code, and now start the glassfish server and go the following URL with two different browsers.

http://localhost:8080/webSocketSample/index.html 


If the application is successfully connected to the server the Output console will show a message "System: You are now connected to the Map Server!!!"

Now send a message with one browser and the message will be broadcast to all the application that are connected with the server.



You have successfully Implemented Simple Application with websockets, You can Find the Source Code at following guthub location

https://github.com/ycrnet/WEbSocketsWithGlassFish

Thank You!

Please Feel free to contact me anytime... :)


0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!