Commit 8e2f7b07 by huyi

添加websocket

parent 915e25d4
...@@ -54,6 +54,16 @@ ...@@ -54,6 +54,16 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- webSocket推送 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.fhkj.oltinspection; package com.fhkj.oltinspection;
import com.fhkj.oltinspection.controller.PushInfoController;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication @SpringBootApplication
public class DemoApplication { public class DemoApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args); ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
PushInfoController.setApplicationContext(applicationContext);
} }
} }
package com.fhkj.oltinspection.config;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String originHeader = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,POST, PUT, DELETE, OPTIONS, HEAD");
response.setHeader("Access-Control-Max-Age", "1209600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization,X-Codingpedia");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req,res);
}
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
package com.fhkj.oltinspection.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by jack on 2017/10/25.
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//super.addViewControllers(registry);
registry.addViewController("/ws").setViewName("/ws");
registry.addViewController("/chat").setViewName("/chat");
}
}
package com.fhkj.oltinspection.config;
/**
* Created by jack on 2017/10/25.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 使用@ServerEndpoint创立websocket endpoint
* 首先要注入 ServerEndpointExporter,
* 这个bean会自动注册使用了 @ServerEndpoint 注
* 解声明的 Web Socket endpoint。
* 要注意,如果使用独立的 Servlet 容器,
* 而不是直接使用 Spring Boot 的内置容器,
* 就不要注入 ServerEndpointExporter,
* 因为它将由容器自己提供和管理
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
\ No newline at end of file
package com.fhkj.oltinspection.controller;
import javax.websocket.server.ServerEndpoint;
import com.fhkj.oltinspection.util.GetHttpSessionConfigurator;
import org.springframework.stereotype.Component;
import org.springframework.context.ApplicationContext;
import javax.servlet.http.HttpSession;
// import javax.servlet.http.HttpSession;
import javax.websocket.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/pushInfo", configurator = GetHttpSessionConfigurator.class)
@Component
public class PushInfoController {
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<PushInfoController> webSocketSet = new CopyOnWriteArraySet<PushInfoController>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private static Map<String, Session> map = new HashMap<>();// 存放当前登陆用户的session
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
private static ApplicationContext applicationContext;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
System.out.println("name is : "+ httpSession.getAttribute("name"));
System.out.println("the session is : "+session.getId());
System.out.println("session content is : "+session.getId());
System.out.println("httpSession is : "+httpSession.getId());
// 获取路径传过来的username
String str = session.getQueryString();
System.out.println(str + "======");
String sendUser = str.split("=")[1];
map.put(sendUser, session);
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount() + "连接人id是:" + sendUser);
try {
sendMessage(""); // 发送消息的方法
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* @return the applicationContext
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* @param applicationContext the applicationContext to set
*/
public static void setApplicationContext(ApplicationContext applicationContext) {
PushInfoController.applicationContext = applicationContext;
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); // 从set中删除
subOnlineCount(); // 在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
PushInfoController.onlineCount++;
}
public static synchronized void subOnlineCount() {
PushInfoController.onlineCount--;
}
}
package com.fhkj.oltinspection.interceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fhkj.oltinspection.pojo.Result;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 身份颜色拦截器
*/
@Component
public class AuthInterceptor implements HandlerInterceptor {
private final static Log log = LogFactory.getLog(AuthInterceptor.class);
private final ObjectMapper objectMapper;
private final RestTemplateBuilder restTemplateBuilder;
@Autowired
public AuthInterceptor(ObjectMapper objectMapper, RestTemplateBuilder restTemplateBuilder) {
this.objectMapper = objectMapper;
this.restTemplateBuilder = restTemplateBuilder;
}
/**
* @return the log
*/
public static Log getLog() {
return log;
}
/**
* @return the restTemplateBuilder
*/
public RestTemplateBuilder getRestTemplateBuilder() {
return restTemplateBuilder;
}
private void returnResult(HttpServletResponse response, Result result) throws IOException {
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.getWriter().print(objectMapper.writeValueAsString(result));
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Hanlder)
throws Exception {
try {
// 如果request请求头或是url中未包含token 验证失败
String token = request.getHeader("token");
if (null == token) {
token = request.getParameter("token");
}
if (token == null || token.isEmpty()) {
returnResult(response, new Result("token为空"));
return false;
}
// 使用身份认证服务验证token
/*RestTemplate client = restTemplateBuilder.build();
Map<String, String> postParam = new HashMap<>();
postParam.put("Token", token);
TokenAuthResult tar = client.postForObject(tokenAuthURL, postParam, TokenAuthResult.class);
if (!tar.getFlag()) {
returnResult(response, new Result(ErrorCode.RET_NOT_LOGIN));
return false;
}*/
return true;
} catch (Exception e) {
e.printStackTrace();
response.sendError(HttpStatus.UNAUTHORIZED.value());
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
package com.fhkj.oltinspection.util;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
/**
* Created by jack on 2017/10/25.
*/
/**
* 解决websocket获取不到session的问题
* 参考:http://www.cnblogs.com/jarviswhj/p/4227559.html
* http://www.cnblogs.com/zhaoww/p/5119706.html
*/
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment