Skip to content

Websocket

VishnuPriya2297 edited this page Sep 20, 2019 · 14 revisions

WebSocket

WebSocket is a communications protocol for a persistent, bi-directional, full-duplex TCP connection from a user’s web browser to a server.

A WebSocket connection is initiated by sending a WebSocket handshake request from a browser’s HTTP connection to a server to upgrade the connection.

Along with the upgrade request header, the handshake request includes a 64-bit Sec-WebSocket-Key header.

The server responds with a hash of the key in a Sec-Websocket-Auth header.

This header exchange prevents a caching proxy from resending previous WebSocket exchanges.

Interfaces

  • WebSocket: The primary interface for connecting to a WebSocket server and then sending and receiving data on the connection.

  • CloseEvent: The event sent by the WebSocket object when the connection closes.

  • MessageEvent: The event sent by the WebSocket object when a message is received from the server.

Get Started with Web Socket in Spring Boot Application:

  • First of all, we will set up Java project for this. The pom.xml file will contain just two dependencies we need at the moment.

We just included spring-boot-starter-web and spring-boot-starter-websocket into the project and that’s pretty enough to be able to receive messages from outside.

  • Next step is to configure WebSockets. Create class WebSocketConfiguration where we will put all settings we need to start with sockets.

@Configuration @EnableWebSocketMessageBroker public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer{ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/socket") .setAllowedOrigins("*") .withSockJS(); }

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app")
            .enableSimpleBroker("/chat");
}

} `

Here we define the endpoint, that our clients will use to connect to the server. So, the URL for connection will be http://localhost:8080/socket/.

We allow the server to receive requests from any origin. For that we will use not “clean” websockets, but with SockJS.

@Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app") .enableSimpleBroker("/chat"); }

when our client will send message through the socket, the URL to send will look approximately like this: http://localhost:8080/app/…/…

Important: For now we will have just one subscription — /chat. So clients will subscribe to this subscription and will wait from messages from the server.

  • We need to add before starting using WebSockets — is the controller.

The same as** @RequestMapping for RestController we need to use @MessageMapping** for websockets. So, here we set up @MessageMapping(“/send/message”), and once this URL will be triggered, we will simply send message to all clients subscribed to /chat subscription.

Thats it for the backend.

For Front-end i.e in our Angular application, we need to install some dependencies.

  • Inside the project we have to install tree libraries with commands:

npm install stompjs; npm install sockjs-client npm install jquery (just to quickly access the DOM elements) npm i net -S

  • app.component.ts

import { Component } from '@angular/core'; import * as Stomp from 'stompjs'; import * as SockJS from 'sockjs-client'; import $ from 'jquery';

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { private serverUrl = 'http://localhost:8080/socket' private title = 'WebSockets chat'; private stompClient;

constructor(){ this.initializeWebSocketConnection(); }

initializeWebSocketConnection(){ let ws = new SockJS(this.serverUrl); this.stompClient = Stomp.over(ws); let that = this; this.stompClient.connect({}, function(frame) { that.stompClient.subscribe("/chat", (message) => { if(message.body) { $(".chat").append("

"+message.body+"
") console.log(message.body); } }); }); }

sendMessage(message){ this.stompClient.send("/app/send/message" , {}, message); $('#input').val(''); }

}

  • So, in the initializeWebSocketConnection() method we define let ws = new SockJS(this.serverUrl). And our serverUrl is http://localhost:8080/socket. So, this is the endpoint that we added in the registerStompEndpoints() method in the server code. After that we told our stompClient to subscribe to the “/chat” channel, that is defined in the
    WebSocketConfiguration class in Java application.

Whenever some server sends messages to the channel “/chat”, all clients that are currently subscribed to it — will receive those messages.

  • Next important element is **sendMessage(message) **method in app.component.ts. Here we simply take the message submitted from the input in HTML file, and with the help of stompClient , We send this message to the “/app/send/message” route defined in the WebSocketController in Java as a value of @MessageMapping in onReceivedMessage method.

  • Whenever the client sends message to “/app/send/message” → this message at the same time is sent to all clients subscribed to the “/chat” channel.

That's it.

Quick Steps:

  1. Run the Spring Boot & Angular application.
  2. Go to the bidding page and start putting your bids.
  3. The Bid amount and number of days are updated in real-time for all user who views the same bid product.

Happy Bidding

Clone this wiki locally