Searching...
Sunday, 14 December 2014

Java EE WebSocket Simple example

02:27

WebSocket is a protocol which allows for communication between the client and the server/endpoint using a single TCP connection. The advantage WebSocket has over HTTP is that the protocol is full-duplex (allows for simultaneous two-way communcation).

Here is one simple example to create a WebSocket endpoint and communicate it from a client.

Softwares Used

Java 1.7, Apache Tomcat, Eclipse

1. Create a Maven project with webapp archetype.

image

2.Create a WebSocket end point.

package com.pretech.test.websockets;
 
import java.io.IOException;
 
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
 
@ServerEndpoint("/websocket")
public class WebSocketTest {
 
    @OnMessage
    public void onMessage(String message, Session session) throws IOException,
            InterruptedException {
        System.out.println("User input: " + message);
        session.getBasicRemote().sendText("Hello world Mr. " + message);
        // Sending message to client each 1 second
        for (int i = 0; i <= 25; i++) {
            session.getBasicRemote().sendText(i + " Message from server");
            Thread.sleep(1000);
 
        }
    }
 
    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }
 
    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}

@ServerEndpoint annotation is used at type level and defines the current class as a websocket server endpoint. The value used in this annotation represents the URL where the endpoint will be listening for client connections

3. Create an html page

<!DOCTYPE html>
<html>
<head>
<title>Pretech blog testing web sockets</title>
</head>
<body>
    <div>
        <input type="text" id="userinput" /> <br> <input type="submit"
           value="Send Message to Server" onclick="start()" />
    </div>
    <div id="messages"></div>
    <script type="text/javascript">
        var webSocket = new WebSocket(
                'ws://localhost:8080/pretech-websocket-example-1.0-SNAPSHOT/websocket');

        webSocket.onerror = function(event) {
            onError(event)
        };

        webSocket.onopen = function(event) {
            onOpen(event)
        };

        webSocket.onmessage = function(event) {
            onMessage(event)
        };

        function onMessage(event) {
            document.getElementById('messages').innerHTML += '<br />'
                    + event.data;
        }

        function onOpen(event) {
            document.getElementById('messages').innerHTML = 'Now Connection established';
        }

        function onError(event) {
            alert(event.data);
        }

        function start() {
            var text = document.getElementById("userinput").value;

            webSocket.send(text);
            return false;
        }
    </script>
</body>
</html>

4. Build and deploy the war

Build the maven project and deploy the war in to tomcat server. Once the server is started hit the blow url.

http://localhost:8080/pretech-websocket-example-1.0-SNAPSHOT/hello.html

We will see the connection established message in the screen, now enter your name and submit the request.

image

image

 

5. Download this example

 

Download WebSoket Example

 

Ref: Netbeans

0 comments: