A Simple WebSocket in Java
WebSocket is a protocol to send full-duplex messages over a single TCP connection.
Once the connection is established between client and server, the same connection will be used to communicate for multiple times by both client and server.
Here client and server acts as two end points and they will exchange the data over a single connection.
Note: In order to run these programs, one should have web socket enables server like jetty 9.2.X, Firefox 47 and JDK7 and above.
WebSocket Server End point:
Server will just print the received message and send an ACK back.
/** * */ package com.websocket; import java.io.IOException; import javax.enterprise.context.ApplicationScoped; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * @author prabhu kvn * */ @ApplicationScoped @ServerEndpoint("/server") public class WebSocketSimpleServer { /** * */ public WebSocketSimpleServer() { // TODO Auto-generated constructor stub } /* * (non-Javadoc) * * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, * javax.websocket.EndpointConfig) */ @OnOpen public void onOpen(Session session, EndpointConfig ednpointConfig) { System.out.println("--- On Open Call ---Session ID---" + session.getId()); } @OnClose public void onClose(Session session) { System.out.println("--- On Close Call--"); } @OnMessage public void onMessage(String message, Session session) { try { System.out.println("Server Received:" + message); session.getBasicRemote().sendText( "(-- Server ACK --"+message+")"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A Client End Point:
This will establish a connection and reuse same connection for sending messages:
/** * */ package com.websocket; import java.io.IOException; import java.net.URI; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; /** * @author prabhu kvn * */ @ClientEndpoint public class WSSimpleClient { /** * */ public WSSimpleClient() { // TODO Auto-generated constructor stub } private static Object waitLock = new Object(); @OnMessage public void onMessage(String message) { System.out.println("Client Received:" + message); } public static void main(String[] args) { for (int i = 0; i < 1; i++) { connectAndSend(); } } /** * */ private static void connectAndSend() { WebSocketContainer container = null;// Session session = null; try { long startTime = System.currentTimeMillis(); container = ContainerProvider.getWebSocketContainer(); session = container .connectToServer( WSSimpleClient.class, URI.create("ws://localhost:8888/websockethome/server")); // send multiple data sets on same connection for(int j=0;j<100;j++){ session.getBasicRemote().sendText("Client text...."+j); } System.out.println("Total Time:" + (System.currentTimeMillis() - startTime)+" ms"); wait4TerminateSignal(); } catch (DeploymentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void wait4TerminateSignal() { synchronized (waitLock) { try { waitLock.wait(100); } catch (InterruptedException e) { } } } }
Play with I and j values in above program to under stand working of websockets.
Scenario 1: i=1 and j=100 , This will establish a connection once and reuse the same connection to send 100 messages.
Scenario 2: i=10 and j=1, This will try to establish the connection 10 times, but it will get same connection for all the request. Observe the first connection against consecutive connection times.
Maven Pom Entries:
<!-- Java ee dependency --> javax javaee-api 7.0 org.apache.httpcomponents httpclient 4.5.1 <!-- Jetty Dependencies --> jetty jetty-plus 6.0.2 org.eclipse.jetty jetty-annotations 9.3.8.v20160314 <!-- Tyrus websoket client support --> org.glassfish.tyrus.bundles tyrus-standalone-client 1.12 org.glassfish.tyrus.bundles tyrus-standalone-client-jdk 1.12 org.glassfish javax.json 1.0.4 websockethome org.apache.maven.plugins maven-compiler-plugin 2.0.2 ${java.version} ${java.version} org.eclipse.jetty jetty-maven-plugin 9.2.11.v20150529 10 /websockethome 8888
>mvn jetty:run will start the server on 8888