Web Socket in Spring Boot
Posted By : Anil Kumar | 26-May-2018
Introduction:
Socket programming or web socket is used for communication between the applications server and client.
Java Socket programming is of two types of connection-oriented or connectionless.
1. Socket and ServerSocket classes are used for connection-oriented socket programming.
Socket class
Important methods
Method:
1) public InputStream getInputStream()
returns the InputStream attached to this socket.
2) public OutputStream getOutputStream()
returns the OutputStream attached to this socket.
3) public synchronized void close()
closes this socket
ServerSocket class:
The ServerSocket class is used to create a server socket.
That socket object is used to establish communication with the clients/users.
Important methods:
1) public Socket accept()
2) public synchronized void close()
closes the server socket.
Example:
Let's go with a simple java socket programme in which users sends a text and server receives that text.
1. Create a web config file
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConfig.class);
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
try {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
catch(Exception e){
LOGGER.error("unable to send data with socket connection: "+e.getMessage());
}
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
LOGGER.info("registry added");
try {
registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
}
catch (Exception e){
LOGGER.error("unable to connect socket connection: "+e.getMessage());
}
}
}
2. Create a Web Socket class with @EnableScheduling to auto update the data
and push the data on the client side.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import com.accounts.mapping.URLMapping;
import com.accounts.service.MarketDataService;
@Controller
@Component
@Configuration
@EnableScheduling
public class WebSocketController {
@Autowired
MarketDataService marketDataService;
@Scheduled(fixedDelay=3000)
@MessageMapping(URLMapping.MARKET_DATA)
@SendTo("/topic"+ URLMapping.MARKET_DATA)
public ResponseEntity<Object> fetchMarketData() {
return marketDataService.fetchMarketData();
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Anil Kumar
Anil is a Web Developer who specializes in creating dynamic and beautiful web projects and has good experience of working in distributed teams.