Welcome to my Tomcat tutorials website!

domenica 4 maggio 2014

Tomcat Websocket example

A WebSocket is a full-duplex communication mechanism that allows both textual and binary messages to be sent between clients and servers, without the HTTP request/response life cycle. WebSockets allow either the client or the server to send a message at any time, providing an asynchronous solution for working with data while the user is performing a task.
Websockets API are included in Tomcat 7 Web server distribution so you don't have to download any extra library:

In this tutorial we will show how to create a WebSocket example using Apache Tomcat and Eclipse.
Start by creating on Eclipse a new Dynamic project named websocket-example:
We will now create a server side class named WebSocketDemo that is going to echo messages from a Javascript client:
package com.sample;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/echo")
public class WebSocketDemo {

    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(msg, last);
            }
        } catch (IOException e) {
            try {
                session.close();
            } catch (IOException e1) {
                // Ignore
            }
        }
    }


}
The @ServerEndpoint annotation accepts a String-based path attribute, which is used to indicate the URI at which the server is available to accept client messages. Therefore, when the server is started, the value of the path attribute would be appended to the end of the context path and application name in which the WebSocket resides.
By initiating a call to that URL, one method, annotated with @OnMessage, will be invoked to process the message that is sent.
Here is the index.jsp file which contains a Javascript code and a form where you can enter a message:
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        <meta charset="utf-8">
        <title>Your First WebSocket!</title>
        <script language="javascript" type="text/javascript">
            
            var wsUri = "ws://localhost:8080/websocket-example/echo";
            
            function init() {
                output = document.getElementById("output");
            }
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                    onOpen(evt)
                };
                websocket.onmessage = function(evt) {
                    onMessage(evt)
                };
                websocket.onerror = function(evt) {
                    onError(evt)
                };
            }
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
                doSend(textID.value);
            }
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            }
            function onError(evt) {
                writeToScreen('ERROR: ' + evt.data);
            }
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                websocket.send(message);
                //websocket.close();
            }
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                 
                output.appendChild(pre);
            }
            window.addEventListener("load", init, false);
        </script>
        <h1 style="text-align: center;">Hello World WebSocket Client</h2>
        <br>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
            </form>
        </div>
        <div id="output"></div>
</body>
</html>

In this example, the message contained in the "message" input field will be sent as text message to the Websocket available at:
var wsUri = "ws://localhost:8080/websocket-example/echo";

Now startup Tomcat and deploy the application. Once that you have entered the message in the text field you should expect to read the echo message on the Web page:

14 commenti:

  1. Hello,
    I have implement the code, as per your suggection,
    But i can't produce the output like your screen.
    Please help me.
    Thanks in advance.

    RispondiElimina
  2. I've follow exactly the entire procedure and I get an error "ERROR: undefined" in jsp page at execution time. Your example is very similar to the echo server sample found in the book websocket programming (Oracle Press) where I get the same error.
    In your explanation I've found something wrong regard the websocket jar that in my case in not included in the tomcat lib directory.

    RispondiElimina
  3. Questo commento è stato eliminato dall'autore.

    RispondiElimina
  4. Questo commento è stato eliminato dall'autore.

    RispondiElimina
  5. it is not running in tomcat 8


    ERROR: undefined

    ERROR: undefined

    ERROR: undefined

    ERROR: undefined
    error on every send

    RispondiElimina
  6. in case of "ERROR: undefined
    error on every send " , please check the wsUri

    RispondiElimina
  7. boys, the Error:undefined is because your project name on eclipse is not same as in the tutorial. So you have to go to your index.html/ jsp file and change the line

    var wsUri = "ws://localhost:8080/websocket-example/echo";

    to point to your server and endpoint

    RispondiElimina
  8. Sir
    I was working on a linux machine , not with eclipse
    i have given my project name as websocket and i included websocket-api.jar file in tomcat 8.0.33
    So I changed
    var wsUri = "ws://localhost:8080/websocket/echo";
    even though i getting the same error
    ERROR : Undefined
    Pls provide me solutiom

    RispondiElimina
  9. Thank you for the code examples. It got me started. Beginning to understand things now. I think the HTML can be improved. It gives the impression that a WebSocket is one-time use because your javascript creates a new WebSocket every time it sends a message.

    I think better would be:

    function init() {
    output = document.getElementById("output");
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) {
    onOpen(evt)
    };
    websocket.onmessage = function(evt) {
    onMessage(evt)
    };
    websocket.onerror = function(evt) {
    onError(evt)
    };
    }
    function send_message() {
    var message = textID.value;
    writeToScreen("Message Sent: " + message);
    websocket.send(message);
    }

    RispondiElimina
  10. WebSocket connection to 'ws://localhost:8082/Websocket/echo' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

    RispondiElimina
  11. WebSocket connection to 'ws://localhost:8082/Websocket/echo' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

    RispondiElimina
  12. I tried it , and it works perfect...Cool and simple.

    RispondiElimina
  13. it is not working on deployed server

    RispondiElimina