如何调用websocket服务器在春天将消息发送到客户端

时间:2014-08-19 03:09:44

标签: java spring websocket spring-websocket

我的项目使用spring框架

WebSocketConfig.java

@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements  WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
         registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new   WebSocketHandshakeInterceptor());

         registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())
            .withSockJS();
    }

    @Bean
    public WebSocketHandler systemWebSocketHandler(){
        return new SystemWebSocketHandler();
    }

}

SystemWebSocketHandler.java

public class SystemWebSocketHandler implements WebSocketHandler {

private static final Logger logger;

private static final ArrayList<WebSocketSession> users;

static {
    users = new ArrayList<>();
    logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
}

@Autowired
private WebSocketService webSocketService;

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    logger.debug("connect to the websocket success......");
    users.add(session);
    String userName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
    //查询未读消息
    int count = webSocketService.getUnReadNews((String)session.getAttributes().get(Constants.WEBSOCKET_USERNAME));

    session.sendMessage(new TextMessage(count+""));
}

@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

}

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    logger.debug("websocket connection closed......");
    users.remove(session);
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    logger.debug("websocket connection closed......");
    users.remove(session);
}

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

/**
 * 给所有在线用户发送消息
 *
 * @param message
 */
public void sendMessageToUsers(TextMessage message) {
    for (WebSocketSession user : users) {
        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 : users) {
        if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }
}
}

我的jsp客户端

if ('WebSocket' in window) {
            websocket = new WebSocket("ws://localhost:8080/Origami/webSocketServer");
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket("ws://localhost:8080/Origami/webSocketServer");
        } else {
            websocket = new SockJS("http://localhost:8080/Origami/sockjs/webSocketServer");
        }

这是我的websocket代码,效果很好

现在我想在控制器中向客户端发送消息,这是我的控制器

@Controller
public class AdminController {

static Logger logger = LoggerFactory.getLogger(AdminController.class);

@Autowired(required = false)
private AdminService adminService;

@Autowired(required = false)
private SystemWebSocketHandler systemWebSocketHandler;

@RequestMapping("/auditing")
@ResponseBody
public String auditing(HttpServletRequest request){
    String result = "fail";
    int id = Integer.parseInt(request.getParameter("id"));
    String reason = request.getParameter("reason");
    String title = request.getParameter("title");
    String username = request.getParameter("username");
    News news = new News();
    DateTime dateTime = DateTime.now();
    news.setNewsTime(dateTime.toDate());
    news.setState(0);
    news.setUsername(username);
    if(reason.equals("")){
        result = adminService.auditingById(id,"Y");
        news.setNewsContent(String.format(Constants.AUDIT_MESSAGE, username, title, reason));
        adminService.addNewsWithUnAudit(news);
    }else{
        news.setNewsContent(String.format(Constants.UN_AUDIT_MESSAGE,username,title,reason));
        result = adminService.addNewsWithUnAudit(news);
        result = adminService.auditingById(id, "D");
    }
    //SystemServerEndPoint serverEndPoint = new SystemServerEndPoint();
    int unReadNewsCount = adminService.getUnReadNews(username);
    systemWebSocketHandler.sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));
    return result;
}
}

我想打电话

systemWebSocketHandler.sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));

向客户端发送消息但systemWebSocketHandler为空

如何将systemWebSocketHandler注入控制器 或其他一些想法来完成所需的?例如服务器在需要向客户端发送消息时连接到websocketserver并在完成时关闭

我的英语很差,但我正在努力学习

1 个答案:

答案 0 :(得分:-1)

我已经解决了问题

@Controller
public class AdminController {

@Bean
public SystemWebSocketHandler systemWebSocketHandler() {
    return new SystemWebSocketHandler();
}