Web application for instant messaging in JSP with WebSockets

0

I would like to get or build an example as I leave it in the following image:

Thiswillhavetousewebsockets.

Itriedtostudythesubjectofwebsocketsandtorunsomeexamples,butI'mnotluckyatall.

SomedaysagoIfoundseveralexampleswithwebsockets,butallofthemweredirectedtoachatapplication.

Ithentriedtocheckifanyofthesechatsran,butnoneofthemransoIcouldnottrymodifyingachatexampletogetwhatIneed.

DoesanyoneknowifthereisalreadyanexampleofwhatIneedorcanyoutellmethebestwaytobuildit?

I'musingeclipsemarswithTomcat8

PASTECODE:SRC

packagews;importjava.io.IOException;importjava.util.concurrent.atomic.AtomicInteger;importjavax.websocket.server.ServerEndpoint;//importjavax.websocket.OnOpen;//importjavax.websocket.OnClose;//importjavax.websocket.OnMessage;//importjavax.websocket.OnError;//importjavax.websocket.Session;importjavax.websocket.*;@ServerEndpoint(value="/ws")
public class WebSocketAnnotation {
    private static final AtomicInteger sequence = new AtomicInteger(1);
    private final String username;
    private Session session;

    public WebSocketAnnotation() {
        username = "User" + sequence.getAndIncrement();
    }

    // inciar sessao de chat
    @OnOpen
    public void start(Session session) {
        this.session = session;
        String message = "*" + username + "* connected.";
        sendMessage(message);
    }

    @OnClose
    public void end() {
        // clean up once the WebSocket connection is closed
    }

    @OnMessage
    public void receiveMessage(String message) {
        // one should never trust the client, and sensitive HTML
        // characters should be replaced with < > " &
        String reversedMessage = new StringBuffer(message).reverse().toString();
        sendMessage("[" + username + "] " + reversedMessage);
    }

    @OnError
    public void handleError(Throwable t) {
        t.printStackTrace();
    }

    private void sendMessage(String text) {
        // uses *this* object's session to call sendText()
        try {
            this.session.getBasicRemote().sendText(text);
        } catch (IOException e) {
            // clean up once the WebSocket connection is closed
            try {
                this.session.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

FOLDER HTML CODE: WEBCONTENT

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript">

        var websocket = null;

        window.onload = function() { // URI = ws://10.16.0.165:8080/WebSocket/ws
            connect('ws://' + window.location.host + '/WebSockets/ws');
            document.getElementById("chat").focus();
        }

        function connect(host) { // connect to the host websocket
            if ('WebSocket' in window)
                websocket = new WebSocket(host);
            else if ('MozWebSocket' in window)
                websocket = new MozWebSocket(host);
            else {
                writeToHistory('Get a real browser which supports WebSocket.');
                return;
            }

            websocket.onopen    = onOpen; // set the event listeners below
            websocket.onclose   = onClose;
            websocket.onmessage = onMessage;
            websocket.onerror   = onError;
        }

        function onOpen(event) {
            writeToHistory('Connected to ' + window.location.host + '.');
            document.getElementById('chat').onkeydown = function(key) {
                if (key.keyCode == 13)
                    doSend(); // call doSend() on enter key
            };
        }

        function onClose(event) {
            writeToHistory('WebSocket closed.');
            document.getElementById('chat').onkeydown = null;
        }

        function onMessage(message) { // print the received message
            writeToHistory(message.data);
        }

        function onError(event) {
            writeToHistory('WebSocket error (' + event.data + ').');
            document.getElementById('chat').onkeydown = null;
        }

        function doSend() {
            var message = document.getElementById('chat').value;
            if (message != '')
                websocket.send(message); // send the message
            document.getElementById('chat').value = '';
        }

        function writeToHistory(text) {
            var history = document.getElementById('history');
            var line = document.createElement('p');
            line.style.wordWrap = 'break-word';
            line.innerHTML = text;
            history.appendChild(line);
            history.scrollTop = history.scrollHeight;
        }

    </script>
</head>

<body>
<noscript>JavaScript must be enabled for WebSockets to work.</noscript>
<div>
    <div id="container"><div id="history"></div></div>
    <p><input type="text" placeholder="type to chat" id="chat"></p>
</div>
</body>

</html>

Paste CSS CODE: WEBCONTENT

input#chat {
  width: 456px;
  border: 1px solid #AACAAC;
}

#container {
  width: 450px;
}

#history {
  height: 180px;
  border: 1px solid #AACAAC;
  padding: 5px;
  font-family: Courier, monospace;
  font-size: .9em;
  overflow-y: scroll;
  width: 100%;
}

#history p {
  margin: 0;
  padding: 0;
} 
    
asked by anonymous 17.01.2016 / 16:51

0 answers