0

How to pass parameter in HTML5 web-sockets and get this values in java class

I passed parameter like this in Chat.initialize function

  Chat.connect('ws://' + window.location.host + '/examples/websocket/chat?id=man');

my JS code is:

    var Chat = {};

    Chat.socket = null;

    Chat.connect = (function(host) {
        if ('WebSocket' in window) {
            Chat.socket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            Chat.socket = new MozWebSocket(host);
        } else {
            Console.log('Error: WebSocket is not supported by this browser.');
            return;
        }

        Chat.socket.onopen = function () {
            Console.log('Info: WebSocket connection opened.');
            document.getElementById('chat').onkeydown = function(event) {
                if (event.keyCode == 13) {
                    Chat.sendMessage();
                }
            };
        };

        Chat.socket.onclose = function () {
            document.getElementById('chat').onkeydown = null;
            Console.log('Info: WebSocket closed.');
        };

        Chat.socket.onmessage = function (message) {
            Console.log(message.data);
        };
    });

    Chat.initialize = function() {
        if (window.location.protocol == 'http:') {
            Chat.connect('ws://' + window.location.host + '/examples/websocket/chat?id=man');
        } else {
            Chat.connect('wss://' + window.location.host + '/examples/websocket/chat?id=man');
        }
    };

    Chat.sendMessage = (function() {
        var message = document.getElementById('chat').value;
        if (message != '') {
            Chat.socket.send(message);
            document.getElementById('chat').value = '';
        }
    });

    var Console = {};

    Console.log = (function(message) {
        var console = document.getElementById('console');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.innerHTML = message;
        console.appendChild(p);
        while (console.childNodes.length > 25) {
            console.removeChild(console.firstChild);
        }
        console.scrollTop = console.scrollHeight;
    });

    Chat.initialize();


    document.addEventListener("DOMContentLoaded", function() {
        // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
        var noscripts = document.getElementsByClassName("noscript");
        for (var i = 0; i < noscripts.length; i++) {
            noscripts[i].parentNode.removeChild(noscripts[i]);
        }
    }, false);

And my java class is like this,But request.getParameter("id"); giving null value.

       public class ChatAnnotation extends HttpServlet{
String name;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
             name = request.getParameter("id");

          //giving null values here.                    
}
private static final Log log = LogFactory.getLog(ChatAnnotation.class);

private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
        new CopyOnWriteArraySet<>();

private final String nickname;
private Session session;


public ChatAnnotation() {
    nickname = name;
}


@OnOpen
public void start(Session session) {
    this.session = session;
    connections.add(this);
    String message = String.format("* %s %s", nickname, "has joined.");
    broadcast(message);
}


@OnClose
public void end() {
    connections.remove(this);
    String message = String.format("* %s %s",
            nickname, "has disconnected.");
    broadcast(message);
}


@OnMessage
public void incoming(String message) {
    // Never trust the client
    String filteredMessage = String.format("%s: %s",
            nickname, HTMLFilter.filter(message.toString()));
    broadcast(filteredMessage);
}




@OnError
public void onError(Throwable t) throws Throwable {
    log.error("Chat Error: " + t.toString(), t);
}


private static void broadcast(String msg) {
    for (ChatAnnotation client : connections) {
        try {
            synchronized (client) {
                client.session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            log.debug("Chat Error: Failed to send message to client", e);
            connections.remove(client);
            try {
                client.session.close();
            } catch (IOException e1) {
                // Ignore
            }
            String message = String.format("* %s %s",
                    client.nickname, "has been disconnected.");
            broadcast(message);
           }
       }
    }
  }

How can I overcome this problem.
Thanks for any help.

user2976215
  • 51
  • 1
  • 8
  • Idea is websocket is not to pass the parameters as url values. So first establish the websocket and then send what ever information you want. – dinesh707 Jan 07 '14 at 15:00
  • link might help : http://www.byteslounge.com/tutorials/java-ee-html5-websocket-example – Kamlesh Arya Jan 07 '14 at 15:02
  • @dinesh707 Now I updated with js code,Now can u please tell to me how to send parameter id – user2976215 Jan 07 '14 at 15:07
  • 3
    your java code does not make sense - you don't need to implement HttpServlet and WebSocket does not use POST at all, so ... you should start with some simple example and try to modify it. And after you do that, take a look at Session.getPathParameters() and @javax.websocket.PathParam. Or if you insist on having query param, you should take a look at Session.getRequestParameterMap() or can always do Session.getRequestURI() and parse it by yourself. – Pavel Bucek Jan 08 '14 at 08:46
  • you can start with this one: http://search.maven.org/#artifactdetails%7Corg.glassfish.tyrus.samples%7Ctyrus-sample-chat%7C1.3.3%7Cwar – Pavel Bucek Jan 08 '14 at 08:57

0 Answers0