What is a web socket with example

WebSocket is used for bidirectional communication between the server and the client.
We need this when there is a need to two directional communication. HTTP is single directional.
Sometimes you might need the server to push data to the client without client request which is not possible via http. Now days websocket is supported in all the browsers.

Here is an example using Spring and Javascript. This is plain web socket withot using Stomp and SockJS.

connectWebsocketplain(){
ws: WebSocket;
this.ws = new WebSocket('ws://localhost:8080/name');
this.ws.onopen = function () {
console.log('on open connection')
};
this.ws.onmessage = function (event: any) {
console.log('on message' + event.data)
};
this.ws.onclose = function () {
console.log("Connection is closed...");
};
}

Spring code for websocket

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class SocketHandler extends TextWebSocketHandler {

    List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws InterruptedException, IOException {
        for (WebSocketSession webSocketSession : sessions) {
            webSocketSession.sendMessage(new TextMessage("Hello Client"+System.currentTimeMillis()));
        }
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // the messages will be broadcasted to all users.
        sessions.add(session);
    }
    public void sendToClient() {
        for (WebSocketSession webSocketSession : sessions) {
            try {
                if (webSocketSession.isOpen()) {
                    webSocketSession.sendMessage(new TextMessage("Hello "+System.currentTimeMillis()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class SocketConfig implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(socketHandler(), "/name").setAllowedOrigins("*");
    }
    @Bean
    public SocketHandler socketHandler() {
        return new SocketHandler();
    }
}

Schedular to publish task in interval
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduleTaskSoket {
    @Autowired
    private SocketHandler handler;
    @Scheduled(fixedRate = 5000)
    public void trigger() {
        handler.sendToClient();
    }
}

No comments:

Post a Comment