/java/

Web Socket. Simple example. String message.

2015-05-31 17:50:14

GitHub

frontend: Html 5 WebSocket

<!DOCTYPE html>

<html>
<head>
<title>Web Socket: String Message</title>
</head>
<body>
<div>
<input onclick='"start()"/' type='"submit"' value='"Start"'/>
</div>
<div id='"messages"'></div>
<script type='"text/javascript"'>

    var webSocket = new WebSocket('ws://localhost:8080/app/websocket/message');

    webSocket.onerror = function (event) {
        console.log(event);
        alert('Error');
    };

    webSocket.onopen = function (event) {
        console.log(event);
        alert('Connection established');
    };

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

    function start() {
        webSocket.send('hello');
        return false;
    }

</script>
</body>
</html>

backend: Jee, javax.websocket

package btbw.socket;

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/message")
public class StringWebSocket {

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {

        System.out.println("Received: " + message);

        session.getBasicRemote().sendText("Michał Btbw");

        for (int i = 0; i &lt; 3; i++) {
            Thread.sleep(2000);
            session.getBasicRemote().sendText("Michał Btbw " + i);
        }

        session.getBasicRemote().sendText("End");
    }

    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }

    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}