Using Spring Boot as the basic framework, Spring Security as the Security framework, WebSocket as the communication framework, to achieve point-to-point chat and group chat.

###2/ Use MongoDB to store data (optional) :

< properties > < Java version > 1.8 < / Java version > < thymeleaf. Version > 3.0.0. RELEASE < / thymeleaf version > < thymeleaf - layout - the dialect version > 2.0.0 < / thymeleaf - layout - the dialect. Version > < / properties > < dependencies > <! -- WebSocket dependency, > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <! --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <! MongoDB database --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <! --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId> Lombok </artifactId> <version>1.16.16</version> </dependency> <dependency> <groupId>com.alibaba</groupId> The < artifactId > fastjson < / artifactId > < version > 1.2.30 < / version > < / dependency > <! Webjars </groupId> <artifactId>webjars-locator</artifactId> < the dependency > < groupId > org. Webjars < / groupId > < artifactId > sockjs - client < / artifactId > < version > 1.0.2 < / version > </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId> Webjars </groupId> <artifactId>jquery</artifactId> </artifactId> The < version > 3.1.0 < / version > < / dependency > < / dependencies >Copy the code

Configuration file contents:

Spring: data: MongoDB: uri: Mongo: / / username: [email protected]:27017 authentication - database: the admin database: chatCopy the code

General program structure, for reference only:

###3/ create application launcher class, EnableWebSocket using @enablewebsocket annotation

@SpringBootApplication @EnableWebSocket public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

###4/ Configuring Spring Security this section is omitted. For details, see Spring Boot Full Stack Development: User Security

###5/ Configure the Web Socket (see section 7)

@Configuration @EnableWebSocketMessageBroker @Log4j public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {/ / here can be written into their Service @ Override public void RegisterStompEndpoints (StompEndpointRegistry StompEndpointRegistry) {// The connection point between the client and the server stompEndpointRegistry.addEndpoint("/any-socket").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry MessageBrokerRegistry) {// Configure the prefix of the path where the client sends the message messageBrokerRegistry.setApplicationDestinationPrefixes("/app"); messageBrokerRegistry.enableSimpleBroker("/topic"); } @Override public void configureWebSocketTransport(final WebSocketTransportRegistration registration) { registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() { @Override public WebSocketHandler decorate(final WebSocketHandler handler) { return new WebSocketHandlerDecorator(handler) { @Override public void AfterConnectionEstablished (final WebSocketSession session) throws the Exception {/ / after the client and the server connection is established, String username = session.getPrincipal().getName(); log.info("online: " + username); super.afterConnectionEstablished(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus CloseStatus) throws Exception {// After the client is disconnected from the server, String username = session.getPrincipal().getName(); log.info("offline: " + username); super.afterConnectionClosed(session, closeStatus); }}; }}); super.configureWebSocketTransport(registration); }}Copy the code

###6/ Point-to-point messages, group messages

@Controller @Log4j public class ChatController { @Autowired private SimpMessagingTemplate template; @messagemapping ("/notice") public void notice(Principal Principal, String message) {// Principal Current login user, // Principal.getName () to get the username of the current user // Send messages to users subscribed to "/topic/notice" and online template.convertAndSend("/topic/notice", message); } // Point-to-point chat @messagemapping ("/chat") public void chat(Principal Principal, String message){// Principal Current login user, // Principal.getName () to get the username of the current user/ / Send the message to subscribe to "/user/topic/chat" And users called toUser template. ConvertAndSendToUser (toUser, "/ topic/chat", content); }}Copy the code

###7/ Client interacts with server

var stompClient = null; function connect() { var socket = new SockJS('/any-socket'); stompClient = Stomp.over(socket); Stompclient. connect({}, function (frame) {// subscribe /topic/notice function (message) { showMessage(JSON.parse(message.body)); }); Subscribe ('/user/topic/chat', function (message) { showMessage(JSON.parse(message.body)); }); }); } $(function () {// create webSocket connect(); $("#send").click(function () {if (target == "TO_ALL") @messagemapping ("/notice") stompclient. send("/app/notice", {}, 'message content '); }else{// Point-to-point message, The message must contain @messagemapping ("/chat") var content = "{'content':' message content','receiver':'anoy'}"; stompClient.send("/app/chat", {}, content); }}); });Copy the code

Log in to three users: Anoyi, Jock and Super administrator. Group messaging test, super administrator group messaging:

Anoyi sends a message to Jock, only Jock receives the message, Anoyi and the super administrator do not receive the message:

###9/ Lightweight DEMO (complete runnable code) Spring Boot Development private Instant Messaging system (WebSocket) (continued) ###10/ references

  • Spring-mongodb official documentation
  • Spring Framework official documentation
  • Spring Guide – stomp websocket

At the end of the article’s welfare

Java data collection of links: pan.baidu.com/s/1pUCCPstP… Password: b2XC More information: 2020 Selected Ali Java, architecture, micro services selected information, plus V ❤ : QWERDD111

This article is published by OpenWrite!