基于Spring mvc 的Websocket 开发

1、Pom.xml

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>

 

2、Spring-servlet,xml

 <context:component-scan base-package="com.websocket"/>

 

3、WebSocketConfig.java

package com.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * Created by HendSame on 11/29/16.
 */
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //允许连接的域,只能以http或https开头
        String[] allowsOrigins = {"*"};

        //WebIM WebSocket通道
        registry.addHandler(allBedWebSocketHandler(),"/websocket/get/all/data/rt").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor());
        registry.addHandler(allBedWebSocketHandler(), "/sockjs/websocket/get/all/data/rt").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS();

        registry.addHandler(bedWebSocketHandler(),"/websocket/get/by/time").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor());
        registry.addHandler(bedWebSocketHandler(), "/sockjs/websocket/get/by/time").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS();

        registry.addHandler(alarmsWebSocketHandler(),"/websocket/get/alarms").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor());
        registry.addHandler(alarmsWebSocketHandler(), "/sockjs/websocket/get/alarms").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS();


        registry.addHandler(overViewWebSocketHandler(),"/websocket/get/overview").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor());
        registry.addHandler(overViewWebSocketHandler(), "/sockjs/websocket/get/overview").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS();

    }
@Bean
public AllBedWebSocketHandler allBedWebSocketHandler() { return new AllBedWebSocketHandler(); } @Bean public BedWebSocketHandler bedWebSocketHandler() { return new BedWebSocketHandler(); } @Bean public AlarmsWebSocketHandler alarmsWebSocketHandler() { return new AlarmsWebSocketHandler(); } @Bean public OverViewWebSocketHandler overViewWebSocketHandler() { return new OverViewWebSocketHandler(); } @Bean public WebSocketHandshakeInterceptor myInterceptor(){ return new WebSocketHandshakeInterceptor(); } }

 

4、BedWebSocketHandler.java

package com.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbkj.nursestation.common.ApiResult;
import com.bbkj.nursestation.common.UserVO;
import com.bbkj.nursestation.site.service.DeviceService;
import com.bbkj.nursestation.site.vi.HospitalBedDataVI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by hy on 11/29/16.
 */
@Component
public class BedWebSocketHandler extends TextWebSocketHandler {

    private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());

    @Autowired
    private DeviceService deviceService;
    //接收文本消息,并发送出去
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        byte[] bytes = message.asBytes();
        String params = new String(bytes);
        JSONObject object=JSON.parseObject(params);
        UserVO userVO = new UserVO();
        userVO = (UserVO) session.getAttributes().get("websocketUser");

        ApiResult<Map<String, Integer>> apiResult = new ApiResult<>(1, "error");
        HospitalBedDataVI hospitalBedDataVI = new HospitalBedDataVI();
        hospitalBedDataVI.setEn(Long.parseLong(object.get("en").toString()));
        hospitalBedDataVI.setPaitenid(Long.parseLong(object.get("paitenid").toString()));
        apiResult = deviceService.getHosptialBedRealTimeData4Websocket(hospitalBedDataVI);
        apiResult.setUser(userVO);
        session.sendMessage(new TextMessage(apiResult.toString()));

    }



    //连接建立后处理
    @SuppressWarnings("unchecked")
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        //处理离线消息
    }
    //抛出异常时处理
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }

        sessions.remove(session);
    }
    //连接关闭后处理
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

        sessions.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : sessions) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : sessions) {
            if (user.getAttributes().get("username").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}

 

5、DeviceService.java

package com.site.service;

import com.bbkj.nursestation.common.ApiResult;
import com.bbkj.nursestation.site.entity.Device;
import com.bbkj.nursestation.site.vi.HospitalBedDataVI;
import com.bbkj.nursestation.site.vo.HosptialBedDataNow;
import com.bbkj.nursestation.site.vo.OverviewVO;

import java.util.List;
import java.util.Map;

/**
 * Created by hy on 11/21/16.
 */
public interface DeviceService {

    ApiResult<Map<String,Integer>> getHosptialBedRealTimeData4Websocket(HospitalBedDataVI hospitalBedDataVI);

}

 

7、Javascript

<script type="text/javascript" src="js/sockjs-1.1.1.min.js"></script>
    <script>
            var websocket;
            if ('WebSocket' in window) {

              //某张床位实时信息接口
              websocket = new WebSocket("ws://192.168.1.114:8099/websocket/get/by/time");
             } else if ('MozWebSocket' in window) {
  
             websocket = new MozWebSocket("ws://192.168.1.114:8099/websocket/get/by/time");
            } else {
      
             websocket = new SockJS("http://192.168.1.114:8099/sockjs/websocket/get/by/time");
             
            }
            websocket.onopen = function (evnt) {
                alert("建立连接");
            };
            websocket.onmessage = function (evnt) {
                alert(evnt.data)
            };
            websocket.onerror = function (evnt) {
            };
            websocket.onclose = function (evnt) {
        }

        $('#send').click(function(e) {
            var params ="{'en':1,'paitenid':1}";
            websocket.send(params);
    });
 </script>

 

posted @ 2016-12-01 12:04  Enast  阅读(1506)  评论(0编辑  收藏  举报