pom.xml

          <!-- websocket -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>

worker.java

public class Worker {
    private String id;
    private String type;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Override
    public String toString() {
        return "Worker [id=" + id + ", type=" + type + "]";
    }
    public Worker() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Worker(String id, String type) {
        super();
        this.id = id;
        this.type = type;
    }

}

 

@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        System.out.println("==========================注册socket");
        //注册websocket server实现类,"/webSocketServer"访问websocket的地址
        registry.addHandler(msgSocketHandle(),
                "/webSocketServer.do").addInterceptors(new WebSocketHandshakeInterceptor());
        //使用socketjs的注册方法
        registry.addHandler(msgSocketHandle(),
                "/sockjs/webSocketServer.do").addInterceptors(new WebSocketHandshakeInterceptor())
                .withSockJS();
    }
    
    @Bean(name = "msgSocketHandle")
    public WebSocketHandler msgSocketHandle(){
        return new MsgScoketHandle();
    }
}

 

public class WebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes)throws Exception {
        System.out.println("Before Handshake");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            Worker worker = (Worker) session.getAttribute("worker");
            if(worker != null)
                attributes.put("worker", worker);
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }
}

 

@Component
public class MsgScoketHandle extends TextWebSocketHandler {
     private static final Map<String,WebSocketSession> workers = new HashMap<String,WebSocketSession>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        //System.out.println("=====================建立连接成功==========================");
        Worker worker  = (Worker) session.getAttributes().get("worker");
        workers.put(worker.getId(), session);
        if(worker != null){
            System.out.println("当前连接用户======"+worker.getId());
        }
    }

    @Override
    public void handleMessage(WebSocketSession session,
            WebSocketMessage<?> message) throws Exception {
            Worker worker = (Worker) session.getAttributes().get("worker");
            System.out.println("收到用户:"+worker.getId()+"的消息");
            System.out.println("===========================================");
    }

    @Override
    public void handleTransportError(WebSocketSession session,
            Throwable exception) throws Exception {
         if (session.isOpen()){
                //关闭session
                try {
                   session.close();
                } catch (IOException e) {
                }
            }
            //移除用户
         Worker worker = (Worker) session.getAttributes().get("worker");
            workers.remove(worker.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session,
            CloseStatus closeStatus) throws Exception {
        workers.remove(session);
        Worker user = (Worker) session.getAttributes().get("user");
        System.out.println(user.getId()+"断开连接");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
        
     /**
     * 发送信息给指定用户
     * @param clientId
     * @param message
     * @return
     */
    public boolean sendMessageToUser(String workerId, TextMessage message) {
        if (workers.get(workerId) == null) return false;
        WebSocketSession session = workers.get(workerId);
        System.out.println("sendMessage:" + session);
        if (!session.isOpen()) return false;
        try {
            session.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 发送消息给所有用户
     * @param messageInfo
     */
    public boolean sendMessageToAllUsers(TextMessage message) {
        boolean allSendSuccess = true;
        Set<String> clientIds = workers.keySet();
        WebSocketSession session = null;
        for (String clientId : clientIds) {
            try {
                session = workers.get(clientId);
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
                allSendSuccess = false;
            }
        }

        return  allSendSuccess;
    }
}

 

@RequestMapping("websocket")
@Controller  
public class UserController {
    @Autowired
    private MsgScoketHandle msgScoketHandle;
    
     @Bean//这个注解会从Spring容器拿出Bean
        public MsgScoketHandle infoHandler() {
            return new MsgScoketHandle();
        }

    
     @RequestMapping("websocket/{userId}")
     public String websocket(HttpServletRequest request)throws Exception{
         String id = request.getParameter("userId");
         Worker worker = new Worker();
         worker.setId(id);
         request.getSession().setAttribute("worker",worker);
         return null;
     }
     
    @RequestMapping("login")
    public String login(HttpServletRequest request)throws Exception{
        Worker worker = new Worker();
        String id = request.getParameter("id");
        String style = request.getParameter("style");
        worker.setId(id);
        worker.setType(style);
        request.getSession().setAttribute("worker",worker);
        return "/send";
    }

    @ResponseBody
    @RequestMapping("sendMsg")
    public String sendMag(String content){
        System.out.println(content+"***************");
        if(content==null){
            return null;
        }else{
            TextMessage textMessage = new TextMessage(content);
            try {
                msgScoketHandle.sendMessageToAllUsers(textMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return content;
        }
    }
}

 大家觉得不错的话可以支持一下我

posted on 2018-07-27 11:23  大橙子最美丽  阅读(1687)  评论(0编辑  收藏  举报