springboot整合websocket

一、pom文件添加依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、增减配置类WebSocketConfig:

@Configuration
public class WebSocketConfig {

	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}
}

三、建立MessageWebSocket类,加上相应注解:

//messageType 1代表主创上线 2代表下线 3代表发广播 4代表提问 5代表回答问题6点赞
@ServerEndpoint(value = "/web/common/MessageWebSocket/{filmId}")//代表访问的url
@Component
public class MessageWebSocket {

	/**
	 * 在线人数
	 */
	public static int onlineNumber = 0;
	/**
	 * 以用户的姓名为key,WebSocket为对象保存起来
	 */
	private static Map<String, MessageWebSocket> clients = new ConcurrentHashMap<String, MessageWebSocket>();
	/**
	 * 会话
	 */
	private Session session;
	/**
	 * 会话key {userId:xxx,userName:xxx,filmId:xxx,isMain:是否是主创}
	 */
	private String identity;

	private User user;

	/**
	 * 建立连接 filmId-- filemId_时间戳/userId
	 * 
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("filmId") String filmId, Session session) {
		// onlineNumber++;
		this.session = session;
		String[] infoArray = filmId.split("_");
		// 设置key
		Identity identityObject = new Identity();
		identityObject.setFilmId(Long.parseLong(infoArray[0]));
		if (infoArray.length == 2) {
			// 表示未登录
			identityObject.setTimstamp(infoArray[1]);
			this.identity = JSONObject.toJSONString(identityObject);
			clients.put(this.identity, this);
			return;
		} else {
			UserService userService = (UserService) ApplicationContextRegister.getApplicationContext()
					.getBean(UserService.class);
			User currentUser = userService.selectByPrimaryKey(Long.parseLong(infoArray[2]));
			identityObject.setUserId(currentUser.getId());
			identityObject.setUserName(currentUser.getNickName());
			this.user = currentUser;
		}
		FilmCreaterRelation filmCreaterRelation = new FilmCreaterRelation();
		filmCreaterRelation.setfId(Integer.parseInt(infoArray[0]));
		filmCreaterRelation.setuId(user.getId().intValue());
		FilmCreaterRelationService filmCreaterRelationService = (FilmCreaterRelationService) ApplicationContextRegister
				.getApplicationContext().getBean(FilmCreaterRelationService.class);
		List<FilmCreaterRelation> filmCreaterRelations = filmCreaterRelationService
				.selectListSelective(filmCreaterRelation);
		try {
			// messageType 1代表主创上线 2代表下线 3代表发广播 4代表提问 5代表回答问题6点赞
			// 如果是主创上线,则发送用户信息
			if (filmCreaterRelations.size() != 0) {
				// 表示是 主创
				identityObject.setIsMain(1);
				Map<String, Object> map = Maps.newHashMap();
				map.put("messageType", 1);
				map.put("user", user);
				map.put("identity", identityObject);
				this.identity = JSONObject.toJSONString(identityObject);
				sendMessageAll(JSON.toJSONString(map), this.identity);
			} else {
				identityObject.setIsMain(0);
				this.identity = JSONObject.toJSONString(identityObject);
			}
			this.identity = JSON.toJSONString(identityObject);
			// 把自己的信息加入到map当中去
			clients.put(this.identity, this);
		} catch (IOException e) {
			System.out.println(this.identity + "上线的时候通知所有人发生了错误");
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("服务端发生了错误" + error.getMessage());
		error.printStackTrace();
	}

	/**
	 * 连接关闭
	 */
	@OnClose
	public void onClose() {
		// onlineNumber--;
		// webSockets.remove(this);
		// 判断identity是否是主创
		try {
			// messageType 1代表主创上线 2代表下线 3代表发广播 4代表提问 5代表回答问题6点赞
			Identity identityObject = JSONObject.parseObject(this.identity, Identity.class);
			if (identityObject.getIsMain() != null && identityObject.getIsMain() == 1) {
				// 表示是主创
				Map<String, Object> map = Maps.newHashMap();
				map.put("messageType", 2);
				map.put("identity", identityObject);
				clients.remove(this.identity);
				sendMessageAll(JSON.toJSONString(map), this.identity);
			} else {
				clients.remove(this.identity);
			}
		} catch (IOException e) {
			System.out.println(this.identity + "下线的时候通知所有人发生了错误");
		}
	}

	/**
	 * 收到客户端的消息
	 *
	 * @param message
	 *            消息
	 * @param session
	 *            会话
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		try {
			// messageType 1代表主创上线 2代表下线 3代表发广播 4代表提问 5代表回答问题6点赞
			// message: { filmId ,content,messageType }
			JSONObject jsonObject = JSON.parseObject(message);
			String messageType = jsonObject.getString("messageType");
			String filmId = jsonObject.getString("filmId");
			String content = jsonObject.getString("content");
			// 回答问题时有
			String questionId = jsonObject.getString("questionId");
			if ("3".equals(messageType)) {
				// 发广播
				Broadcast broadcast = new Broadcast();
				broadcast.setContent(content);
				broadcast.setUserId(this.user.getId());
				broadcast.setUserName(this.user.getNickName());
				broadcast.setFilmId(Long.parseLong(filmId));
				broadcast.setSendTime(DateFormatUtil.dateFormat(new Date(), DateFormatUtil.DATE_TIME_PATTERN));
				BroadcastService broadcastService = (BroadcastService) ApplicationContextRegister
						.getApplicationContext().getBean(BroadcastService.class);
				broadcastService.insertSelective(broadcast);
				MessageCustom messageCustom = new MessageCustom();
				messageCustom.setMessageType("3");
				messageCustom.setBroadcast(broadcast);
				sendMessageAll(JSON.toJSONString(messageCustom), this.identity);
			} else if ("4".equals(messageType)) {
				// 提问
				Questions questions = new Questions();
				questions.setQuestionUserId(this.user.getId());
				questions.setFilmId(Long.parseLong(filmId));
				// 判断是否提问超过三个
				QuestionService questionService = (QuestionService) ApplicationContextRegister.getApplicationContext()
						.getBean(QuestionService.class);
				List<Questions> haveQuestions = questionService.selectListSelective(questions);
				if (!(haveQuestions.size() < 3)) {
					// 不能再提问
					return;
				}
				questions.setQuestion(content);
				questions.setQuestionUserName(this.user.getNickName());
				questions.setQuestionTime(DateFormatUtil.dateFormat(new Date(), DateFormatUtil.DATE_TIME_PATTERN));
				questionService.insertSelective(questions);
				questions = questionService.selectListSelective(questions).get(0);
				questions.setHeadimgurl(this.user.getHeadimgurl());
				MessageCustom messageCustom = new MessageCustom();
				messageCustom.setMessageType("4");
				messageCustom.setQuestions(questions);
				sendMessageAll(JSON.toJSONString(messageCustom), this.identity);
			} else if ("5".equals(messageType)) {
				// 回答
				Answers answers = new Answers();
				answers.setQuestionId(Long.parseLong(questionId));
				answers.setAnswer(content);
				answers.setAnswerUserId(this.user.getId());
				answers.setAnswerUserName(this.user.getNickName());
				answers.setAnswerTime(DateFormatUtil.dateFormat(new Date(), DateFormatUtil.DATE_TIME_PATTERN));
				AnswerService answerService = (AnswerService) ApplicationContextRegister.getApplicationContext()
						.getBean(AnswerService.class);
				answerService.insertSelective(answers);
				answers = answerService.selectListSelective(answers).get(0);
				MessageCustom messageCustom = new MessageCustom();
				messageCustom.setMessageType("5");
				messageCustom.setAnswers(answers);
				messageCustom.setUser(this.user);
				sendMessageAll(JSON.toJSONString(messageCustom), this.identity);
			} else if ("6".equals(messageType)) {
				// 点赞
				QuestionLike questionLike = new QuestionLike();
				questionLike.setQuestionId(Long.parseLong(questionId));
				questionLike.setUserId(this.user.getId());
				QuestionLikeService questionLikeService = (QuestionLikeService) ApplicationContextRegister
						.getApplicationContext().getBean(QuestionLikeService.class);
				questionLikeService.insertSelective(questionLike);
				MessageCustom messageCustom = new MessageCustom();
				messageCustom.setMessageType("6");
				messageCustom.setQuestionLike(questionLike);
				sendMessageAll(JSON.toJSONString(messageCustom), this.identity);
			}
		} catch (Exception e) {
			System.out.println("发生了错误了");
		}

	}

	public void sendMessageTo(String message, String ToUserName) throws IOException {
		for (MessageWebSocket item : clients.values()) {
			if (item.identity.equals(ToUserName)) {
				item.session.getAsyncRemote().sendText(message);
				break;
			}
		}
	}

	public void sendMessageAll(String message, String FromUserName) throws IOException {
		try {
			for (MessageWebSocket item : clients.values()) {
				item.session.getAsyncRemote().sendText(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 返回当前在线主创
	public List<User> getMain(String filmId) {
		List<User> list = new ArrayList<User>();
		for (MessageWebSocket item : clients.values()) {
			// item.session.getAsyncRemote().sendText(message);
			Identity identityObject = JSONObject.parseObject(item.identity, Identity.class);
			if (identityObject.getIsMain() != null && identityObject.getIsMain() == 1
					&& identityObject.getFilmId() == Long.parseLong(filmId)) {
				list.add(item.user);
			}
		}
		return list;
	}

	public static synchronized int getOnlineCount() {
		return onlineNumber;
	}

}

四、前端建立连接的方法:

            connect(){
                let that = this;
                this.ws = new WebSocket(this.path+"10_1563377589585_8");
                console.log("连接测试");
                this.ws.onopen = function(){
                    console.log("已经连通了websocket");
                    that.showMessage("已经连通了websocket");
                };
        
                //接收后台服务端的消息
                this.ws.onmessage = function (evt){
                    var received_msg = evt.data;
                    console.log("数据已接收:" +received_msg);
                    that.showMessage(received_msg);
                };
        
                //连接关闭的回调事件
                this.ws.onclose = function(){
                    console.log("连接已关闭...");
                    that.showMessage("连接已关闭...");
                };
            },
            disconnect(){
                this.ws.close();
            },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值