前言
创新互联长期为数千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为平乡企业提供专业的成都网站制作、网站建设,平乡网站改版等技术服务。拥有10余年丰富建站经验和众多成功案例,为您定制开发。
QQ这类即时通讯工具多数是以桌面应用的方式存在。在没有websocket出现之前,如果开发一个网页版的即时通讯应用,则需要定时刷新页面或定时调用ajax请求,这无疑会加大服务器的负载和增加了客户端的流量。而websocket的出现,则完美的解决了这些问题。
spring boot对websocket进行了封装,这对实现一个websocket网页即时通讯应用来说,变得非常简单。
一、准备工作
pom.xml引入
org.springframework.boot spring-boot-starter-websocket
完整的pom.xml文件代码如下:
<?xml version="1.0" encoding="UTF-8"?>4.0.0 com.example spring-boot-16 0.0.1-SNAPSHOT jar spring-boot-16 Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.3.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket org.springframework.boot spring-boot-devtools runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
二、代码编写
1.创建名为“WebSocketConfig.java”的类来配置websocket,并继承抽象类“AbstractWebSocketMessageBrokerConfigurer”
此类声明“@EnableWebSocketMessageBroker”的注解
package com.example;
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 {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/my-websocket").withSockJS();
}
}
这里配置了以“/app”开头的websocket请求url。和名为“my-websocket”的endpoint(端点)
2.编写一个DTO类来承载消息:
package com.example;
public class SocketMessage {
public String message;
public String date;
}
3.创建App.java类,用于启用spring boot和用于接收、发送消息的控制器。
package com.example;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
@EnableScheduling
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Autowired
private SimpMessagingTemplate messagingTemplate;
@GetMapping("/")
public String index() {
return "index";
}
@MessageMapping("/send")
@SendTo("/topic/send")
public SocketMessage send(SocketMessage message) throws Exception {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
message.date = df.format(new Date());
return message;
}
@Scheduled(fixedRate = 1000)
@SendTo("/topic/callback")
public Object callback() throws Exception {
// 发现消息
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
messagingTemplate.convertAndSend("/topic/callback", df.format(new Date()));
return "callback";
}
}
“send”方法用于接收客户端发送过来的websocket请求。
@EnableScheduling注解为:启用spring boot的定时任务,这与“callback”方法相呼应,用于每隔1秒推送服务器端的时间。
4.在“resources/templates”目录下创建index.html文件:
玩转spring boot——websocket 玩转spring boot——websocket
出处:刘冬博客 http://www.cnblogs.com/goodhelper
消息列表:
内容 时间 {{row.message}} {{row.date}}
除了引用angular.js的CDN文件外,还需要引用sockjs和stomp。
完整的项目结构,如下图所示:

三、运行效果

点击“连接”按钮,出现发送消息的输入框。并接收到服务器端的时间推送。
输入发送内容并点击“发送”按钮后,页面显示出刚才发送的消息。
点击“断开”按钮,则服务器端不会再推送消息。
总结
在开发一个基于web的即时通讯应用的过程中,我们还需考虑session的机制。
还需要一个集合来承载当前的在线用户,并做一个定时任务,其目的是用轮询的方式定时处理在线用户的状态,有哪些用户在线,又有哪些用户离线。
参考:
http://spring.io/guides/gs/scheduling-tasks/
http://spring.io/guides/gs/messaging-stomp-websocket/
代码地址:https://github.com/carter659/spring-boot-16
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。