1. pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. websocket配置类
package cn.longrace.wisdom.common.websocket; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker //注解开启STOMP协议来传输基于代理的消息,此时控制器支持使用@MessageMapping public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 允许使用socketJs方式访问,访问点为webSocketServer,允许跨域 // 在网页上我们就可以通过这个链接 // http://localhost:9999/webSocketServer来和服务器的WebSocket连接 registry.addEndpoint("/webSocketServer").setAllowedOrigins("*"); // 使用stompjs,我在项目中使用的上面那种方式,两种都可以,就是前端连接的方式不用, // 上面那种vue的连接地址是ws开头,下面这种是http开头,例:
// Vue.prototype.$globalWebsocketUrl= ws://localhost:8080/wisdom-classrome/webSocketServer// registry.addEndpoint("/webSocketServer").setAllowedOrigins("*").withSockJS();
} @Override public void configureMessageBroker(MessageBrokerRegistry registry) { ///启动一个简单基于内存的消息代理,表示可以在这三个域上可以向客户端发送消息 registry.enableSimpleBroker("/topic","/user"); //客户端发送想服务器发送消息的时的主题上面要加"/app",以/app 开头的数据会被@MessageMapping拦截 进入方法体 registry.setApplicationDestinationPrefixes("/app"); //给指定用户发送消息的前缀时/user/ registry.setUserDestinationPrefix("/user/"); } }
3. 接收消息和发送消息的控制器类
package cn.longrace.wisdom.common.websocket;
import cn.longrace.wisdom.common.vo.R;
import cn.longrace.wisdom.modules.dataBase.entity.StudentEntity;
import cn.longrace.wisdom.modules.teacher.member.entity.TeacherActivityClassPerformanceEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
/**
*
* @ClassName: WebSocketAction
* @Description: websocket控制层
* @author cheng
* @date 2017年9月27日 下午4:20:58
*/
@RestController
@RequestMapping("webSocket")
public class WebSocketAction{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SimpMessagingTemplate messagingTemplate;
/**
* 接收学生端举手或抢答的消息
* path: /handsUp举手,/rushToAnswer抢答
*/
@MessageMapping("/handsUp")
public void handsUpMessage (@RequestParam(name = "msg")String msg) {
JSONObject jsonObject = JSONObject.parseObject(msg);
String studentId = jsonObject.getString("id");
String name = jsonObject.getString("name");
String teacherId = jsonObject.getString("teacherId");
String type = jsonObject.getString("type");
String path = jsonObject.getString("path");
StudentEntity studentEntity = new StudentEntity();
studentEntity.setId(Long.parseLong(studentId));
studentEntity.setName(name);
studentEntity.setTeacherId(Long.parseLong(teacherId));
System.out.println(type + "chatMessage.getReceiver()------------------"+studentEntity);
// 直接向前端推送消息
messagingTemplate.convertAndSendToUser(studentId, path, studentEntity);
// messagingTemplate.convertAndSendToUser(String.valueOf(studentEntity.getId().longValue()),"/handsUp",studentEntity); // 直接向前端推送消息
}
/**
* 群发
* @param performanceEntity
*/
@GetMapping("/groupSending")
@RequiresRoles("teacher")
public R groupSending (TeacherActivityClassPerformanceEntity performanceEntity) {
String topic = "/topic/"+performanceEntity.getCurriculumId()+"/"+performanceEntity.getGradeId();
// performanceEntity.setType(0);
messagingTemplate.convertAndSend(topic, JSON.toJSONString(performanceEntity));
return R.ok();
}
/**
* 向学生端推送课程id
* @param performanceEntity
* @return
*/
@GetMapping("/pushCurriculumId")
public R pushCurriculumId (TeacherActivityClassPerformanceEntity performanceEntity) {
String topic = "/topic/"+performanceEntity.getGradeId();
messagingTemplate.convertAndSend(topic, JSON.toJSONString(performanceEntity));
return R.ok();
}
/**
* 发消息
*/
@RequestMapping("/sendStudentId")
public void groupSending (@RequestParam(value = "studentId",required = false) Long studentId) {
messagingTemplate.convertAndSend("/topic/comparisonFace", studentId);
}
}