美文网首页
spring+tomcat上的websocket实现

spring+tomcat上的websocket实现

作者: vlsee | 来源:发表于2018-10-31 23:15 被阅读40次

活动上墙时,需要后台主动地向前端推送新收到的消息,前端随之不断刷新消息列表。
这种功能的开发,与websocket技术简直是天作之合。

在pom.xml中需要添加如下依赖

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-websocket</artifactId>
        <version>4.3.5.RELEASE</version>
    </dependency>

总体来说坑不多,也就要注入service,必须有configurator参数,下面直接贴代码,希望以后能看懂。

/*
    @author 米枣
    @date 2018/10/30 20:15
*/
package com.fantasy.controller;

import com.fantasy.entity.Activity;
import com.fantasy.entity.InteractWallMsg;
import com.fantasy.entity.message.resp.ActivityCheckJson;
import com.fantasy.entity.message.resp.InteractWallMsgListJson;
import com.fantasy.entity.message.resp.StatusJson;
import com.fantasy.service.ActivityService;
import com.fantasy.service.InteractWallMsgService;
import net.sf.json.JSONObject;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint(value = "/{service}/{aid}", configurator = SpringConfigurator.class)
public class InteractWallWSController {

    @Resource
    InteractWallMsgService interactWallMsgService;
    @Resource
    ActivityService activityService;

    public static ConcurrentMap<Integer, Session> msgWallConnections = new ConcurrentHashMap<Integer, Session>();
    public static ConcurrentMap<Integer, Session> verifyConnections = new ConcurrentHashMap<Integer, Session>();
    private Session session;
    private Integer aid;

    @OnOpen
    public void onOpen(Session session,  @PathParam(value = "service") String service, @PathParam(value = "aid") Integer aid){

        System.out.println(aid);
        if(service.equals("msgWall")){
            this.session = session;
            msgWallConnections.putIfAbsent(aid, this.session);
            this.aid = aid;

            Activity activity = activityService.getActivityById(aid);
            activity.setInProgress(true);
            activityService.updateActivity(activity);

            List<InteractWallMsg> msgList = interactWallMsgService.getAgreedMsgList(aid, null, -1, null);
            StatusJson msgListStatusJson = new InteractWallMsgListJson("1000", "success", false, msgList);
            sendMessage(session, msgListStatusJson);
            StatusJson checkNecessaryStatusJson = new ActivityCheckJson("1000", "success", activity.getMsgCheckNecessary());
            sendMessage(session, checkNecessaryStatusJson);
        }
        else if(service.equals("verify")){
            this.session = session;
            verifyConnections.putIfAbsent(aid, this.session);
            this.aid = aid;

            Activity activity = activityService.getActivityById(aid);
            StatusJson checkNecessaryStatusJson = new ActivityCheckJson("1000", "success", activity.getMsgCheckNecessary());
            sendMessage(session, checkNecessaryStatusJson);
        }

    }

    @OnClose
    public void onClose(Session session){
        System.out.println("closing...");
        if(msgWallConnections.get(this.aid) == session){
            Activity activity = activityService.getActivityById(this.aid);
            activity.setInProgress(false);
            activityService.updateActivity(activity);

            msgWallConnections.remove(this.aid, this.session);
            this.session = null;
            try{
                session.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        else if(verifyConnections.get(this.aid) == session){
            verifyConnections.remove(this.aid, this.session);
            this.session = null;
            try{
                session.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Throwable t){
        System.out.println("error!!");
        t.printStackTrace();
    }

    public static void sendMessage(Session session, StatusJson msgStatusJson){
        JSONObject jsonObject = JSONObject.fromObject(msgStatusJson);
        try {
            session.getBasicRemote().sendText(jsonObject.toString());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

      本文标题:spring+tomcat上的websocket实现

      本文链接:https://www.haomeiwen.com/subject/jbbztqtx.html