Spring Boot (ii) websocket

Source: Internet
Author: User

Spring boot and WebSocket

1. Broadcast type

1. Use @enablewebsocketmessagebroker to turn on WebSocket support in the configuration class.

Stompendpointregistry.addendpoint ("/endpointwisely"). Withsocketjs (); Registering the node for the STOMP protocol, configuring the developed URL

Stompendpointregistry.enablesimplebroker ("/topic"); Configure the message agent and also the URL prefix of the server-side Send Message

2. In the controller

@Controller

public class wscontroller{

@MessageMapping ("/hello")//Browser request path

@SendTo ("/topic/getresponse")

Public wiselyresponse Say (Wiselymessage message) {

return new Wiselyresponse ("Hello" +message);

}

3. In the page JS

var socket = new Sockjs ('/endpointwisely '); //The node URL configured in config

Stompclient.subscribe ('/topic/getresponse ')//subscription, browser-and server, corresponding to the path of @sendto annotations in the controller

Stompclient.send ('/hello ')//Send message, server-to-browser, corresponding to the path of @messagemapping annotations in the controller

2. Point-to-point

Simpmessagingtemplate is a spring-websocket built-in message sending tool that can send messages to the specified client.

@Controller

public class wscontroller{

@Autowired

Private Simpmessagingtemplate simpmessagingtemplate;

@MessageMapping ("/point2p")//Browser request path

public void Say (String message) {

Simpmessagingtemplate.convertandsendtouser ("User receiving message", "/topic/getresponse", message);

}

}

And JS in the path Stompclient.subscribe ('/user/topic/getresponse '), more than one/user, indicating the sending of messages to the specified user.

Spring Boot (ii) websocket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.