浏览代码

webSocket开发

Administrator 4 年之前
父节点
当前提交
5982984ff8

+ 122 - 120
pom.xml

@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
 	<modelVersion>4.0.0</modelVersion>
@@ -20,35 +21,35 @@
 		<org.aspectj-version>1.6.10</org.aspectj-version>
 		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 	</properties>
-	<profiles>  
-        <profile>  
-            <id>aft_local</id>  
-            <activation>  
-                <activeByDefault>true</activeByDefault>  
-            </activation>  
-            <properties>  
-                <profiles.activation>local</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_dev</id>  
-            <properties>  
-                <profiles.activation>dev</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_prod</id>  
-            <properties>  
-                <profiles.activation>prod</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_test</id>  
-            <properties>  
-                <profiles.activation>test</profiles.activation>  
-            </properties>  
-        </profile>  
-	</profiles> 
+	<profiles>
+		<profile>
+			<id>aft_local</id>
+			<activation>
+				<activeByDefault>true</activeByDefault>
+			</activation>
+			<properties>
+				<profiles.activation>local</profiles.activation>
+			</properties>
+		</profile>
+		<profile>
+			<id>aft_dev</id>
+			<properties>
+				<profiles.activation>dev</profiles.activation>
+			</properties>
+		</profile>
+		<profile>
+			<id>aft_prod</id>
+			<properties>
+				<profiles.activation>prod</profiles.activation>
+			</properties>
+		</profile>
+		<profile>
+			<id>aft_test</id>
+			<properties>
+				<profiles.activation>test</profiles.activation>
+			</properties>
+		</profile>
+	</profiles>
 
 	<dependencies>
 		<!-- spring -->
@@ -70,27 +71,28 @@
 			<version>${org.springframework-version}</version>
 		</dependency>
 		
-        <dependency>  
-            <groupId>javax.annotation</groupId>  
-            <artifactId>jsr250-api</artifactId>  
-            <version>1.0</version>  
-        </dependency> 
-        <!-- hibernate-validator -->
-        <dependency>
-            <groupId>org.hibernate</groupId>
-            <artifactId>hibernate-validator</artifactId>
-            <version>5.4.0.Final</version>
-        </dependency>
-        <dependency>
-     <groupId>javax.xml.bind</groupId>
-     <artifactId>jaxb-api</artifactId>
-     <version>2.3.0</version>
- </dependency>
-<dependency>
-    <groupId>de.dfki.cos.basys.platform.wrapper-bundle-settings</groupId>
-    <artifactId>javax.websocket-api</artifactId>
-    <version>0.2.6</version>
-</dependency>
+
+		<dependency>
+			<groupId>javax.annotation</groupId>
+			<artifactId>jsr250-api</artifactId>
+			<version>1.0</version>
+		</dependency>
+		<!-- hibernate-validator -->
+		<dependency>
+			<groupId>org.hibernate</groupId>
+			<artifactId>hibernate-validator</artifactId>
+			<version>5.4.0.Final</version>
+		</dependency>
+		<dependency>
+			<groupId>javax.xml.bind</groupId>
+			<artifactId>jaxb-api</artifactId>
+			<version>2.3.0</version>
+		</dependency>
+		<dependency>
+			<groupId>de.dfki.cos.basys.platform.wrapper-bundle-settings</groupId>
+			<artifactId>javax.websocket-api</artifactId>
+			<version>0.2.6</version>
+		</dependency>
 		<dependency>
 			<groupId>org.springframework</groupId>
 			<artifactId>spring-webmvc</artifactId>
@@ -117,28 +119,28 @@
 			<artifactId>spring-messaging</artifactId>
 			<version>${org.springframework-version}</version>
 		</dependency>
-		
+
 		<dependency>
-		    <groupId>org.springframework.data</groupId>
-		    <artifactId>spring-data-redis</artifactId>
-		    <version>1.8.3.RELEASE</version>
+			<groupId>org.springframework.data</groupId>
+			<artifactId>spring-data-redis</artifactId>
+			<version>1.8.3.RELEASE</version>
 		</dependency>
-		
+
 		<dependency>
-		    <groupId>org.thymeleaf</groupId>
-		    <artifactId>thymeleaf-spring4</artifactId>
-		    <version>3.0.5.RELEASE</version>
+			<groupId>org.thymeleaf</groupId>
+			<artifactId>thymeleaf-spring4</artifactId>
+			<version>3.0.5.RELEASE</version>
 		</dependency>
 		<dependency>
-		    <groupId>nz.net.ultraq.thymeleaf</groupId>
-		    <artifactId>thymeleaf-layout-dialect</artifactId>
-		    <version>2.2.1</version>
+			<groupId>nz.net.ultraq.thymeleaf</groupId>
+			<artifactId>thymeleaf-layout-dialect</artifactId>
+			<version>2.2.1</version>
 		</dependency>
 		<dependency>
-            <groupId>com.github.theborakompanioni</groupId>
-            <artifactId>thymeleaf-extras-shiro</artifactId>
-            <version>2.0.0</version>
-        </dependency>
+			<groupId>com.github.theborakompanioni</groupId>
+			<artifactId>thymeleaf-extras-shiro</artifactId>
+			<version>2.0.0</version>
+		</dependency>
 		<!-- spring end -->
 
 		<!-- redis begin -->
@@ -341,33 +343,33 @@
 			<artifactId>classmate</artifactId>
 			<version>1.1.0</version>
 		</dependency>
-	    <dependency>
-		    <groupId>com.googlecode.json-simple</groupId>
-		    <artifactId>json-simple</artifactId>
-		    <version>1.1.1</version>
+		<dependency>
+			<groupId>com.googlecode.json-simple</groupId>
+			<artifactId>json-simple</artifactId>
+			<version>1.1.1</version>
 		</dependency>
 		<dependency>
-		    <groupId>org.apache.poi</groupId>
-		    <artifactId>poi-ooxml</artifactId>
-		    <version>3.17</version>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi-ooxml</artifactId>
+			<version>3.17</version>
 		</dependency>
-       <dependency>
- 		 	<groupId>com.aliyun</groupId>
-  			<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
-  			<version>1.0.0</version>
+		<dependency>
+			<groupId>com.aliyun</groupId>
+			<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
+			<version>1.0.0</version>
 		</dependency>
 		<dependency>
 			<groupId>com.aliyun</groupId>
 			<artifactId>aliyun-java-sdk-core</artifactId>
 			<version>3.5.0</version>
 		</dependency>
-        <dependency>
+		<dependency>
 			<groupId>org.apache.httpcomponents</groupId>
 			<artifactId>httpasyncclient</artifactId>
 			<version>4.1.3</version>
 		</dependency>
-        
-        <!-- jpush -->
+
+		<!-- jpush -->
 		<dependency>
 			<groupId>cn.jpush.api</groupId>
 			<artifactId>jiguang-common</artifactId>
@@ -386,9 +388,9 @@
 		</dependency>
 		<!-- javaMail -->
 		<dependency>
-		    <groupId>javax.mail</groupId>
-		    <artifactId>mail</artifactId>
-		    <version>1.4.7</version>
+			<groupId>javax.mail</groupId>
+			<artifactId>mail</artifactId>
+			<version>1.4.7</version>
 		</dependency>
 	</dependencies>
 	<build>
@@ -425,45 +427,45 @@
 					<skip>true</skip>
 				</configuration>
 			</plugin>
-			<plugin>    
-			    <groupId>org.apache.maven.plugins</groupId>    
-			    <artifactId>maven-surefire-plugin</artifactId>    
-			    <version>2.5</version>    
-			    <configuration>    
-			        <skip>true</skip>    
-			    </configuration>    
-			</plugin> 
-			<plugin>  
-                <groupId>org.apache.maven.plugins</groupId>  
-                <artifactId>maven-war-plugin</artifactId>  
-                <version>3.1.0</version>  
-                <configuration>  
-                    <warName>${profiles.activation}</warName>  
-                    <!-- 激活spring profile -->  
-                    <webResources>  
-                        <resource>  
-                            <filtering>true</filtering>  
-                            <directory>src/main/webapp</directory>  
-                            <includes>  
-                                <include>**/**</include>  
-                            </includes>  
-                        </resource>  
-                        <resource>  
-                            <filtering>true</filtering>  
-                            <directory>src/main/resources</directory>
-                            <targetPath>WEB-INF/classes</targetPath>
-                            <includes>  
-                                <include>**/**</include>  
-                            </includes>  
-                        </resource>  
-                    </webResources>  
-                    <warSourceDirectory>src/main/webapp</warSourceDirectory>  
-                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>  
-                </configuration>  
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-surefire-plugin</artifactId>
+				<version>2.5</version>
+				<configuration>
+					<skip>true</skip>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-war-plugin</artifactId>
+				<version>3.1.0</version>
+				<configuration>
+					<warName>${profiles.activation}</warName>
+					<!-- 激活spring profile -->
+					<webResources>
+						<resource>
+							<filtering>true</filtering>
+							<directory>src/main/webapp</directory>
+							<includes>
+								<include>**/**</include>
+							</includes>
+						</resource>
+						<resource>
+							<filtering>true</filtering>
+							<directory>src/main/resources</directory>
+							<targetPath>WEB-INF/classes</targetPath>
+							<includes>
+								<include>**/**</include>
+							</includes>
+						</resource>
+					</webResources>
+					<warSourceDirectory>src/main/webapp</warSourceDirectory>
+					<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
+				</configuration>
 			</plugin>
 		</plugins>
 	</build>
-	
+
 	<repositories>
 		<repository>
 			<id>aliyun-repos</id>
@@ -475,7 +477,7 @@
 	</repositories>
 
 
-    
+
 	<pluginRepositories>
 		<pluginRepository>
 			<id>aliyun-plugin</id>

+ 8 - 8
src/main/java/com/goafanti/admin/bo/OutPublicRelease.java

@@ -1,7 +1,12 @@
 package com.goafanti.admin.bo;
 
-public class OutPublicRelease {
-	private Integer id;
+import com.goafanti.common.model.PublicRelease;
+
+public class OutPublicRelease extends PublicRelease {
+	/**
+	 * 
+	 */
+	private static final long serialVersionUID = 1L;
 	private String nickname;
 	private String aname;
 	private String releaseStarts;
@@ -9,12 +14,7 @@ public class OutPublicRelease {
 	private String releaseEnds;
 	private String createTimes;
 	private Integer status;
-	public Integer getId() {
-		return id;
-	}
-	public void setId(Integer id) {
-		this.id = id;
-	}
+	
 	public String getNickname() {
 		return nickname;
 	}

+ 14 - 2
src/main/java/com/goafanti/admin/controller/AdminReleaseApiController.java

@@ -88,9 +88,21 @@ public class AdminReleaseApiController extends CertifyApiController{
 	 * @return
 	 */
 	@RequestMapping(value = "/dtails", method = RequestMethod.GET)
-	public Result publicReleaseDtails(String id){
+	public Result dtails(Integer id){
 		Result res =new Result();
-		res.setData(publicReleaseService.publicReleaseDtails(id));
+		res.setData(publicReleaseService.dtails(id));
+		return res;
+	}
+	
+	
+	/**
+	 * 外出申请详情
+	 * @return
+	 */
+	@RequestMapping(value = "/followDtails", method = RequestMethod.GET)
+	public Result followDtails(String id){
+		Result res =new Result();
+		res.setData(publicReleaseService.followDtails(id));
 		return res;
 	}
 	

+ 3 - 1
src/main/java/com/goafanti/admin/service/PublicReleaseService.java

@@ -25,12 +25,14 @@ public interface PublicReleaseService {
 
 	int pushPublicReleaseClockIn(Integer id);
 
-	OutPublicRelease publicReleaseDtails(String id);
+	OutPublicRelease dtails(Integer id);
 
 	Object publicReleaseStatistics(InputPublicStatistics in);
 
 	Object publicReleaseListDtails(InputPublicDtails in);
 
+	OutPublicRelease followDtails(String id);
+
 
 
 }

+ 6 - 1
src/main/java/com/goafanti/admin/service/impl/PublicReleaseServiceImpl.java

@@ -153,7 +153,12 @@ public class PublicReleaseServiceImpl extends BaseMybatisDao<PublicReleaseMapper
 	}
 
 	@Override
-	public OutPublicRelease publicReleaseDtails(String id) {
+	public OutPublicRelease dtails(Integer id) {
+		return	publicReleaseMapper.selectByid(id); 
+	}
+	
+	@Override
+	public OutPublicRelease followDtails(String id) {
 		return	publicReleaseMapper.selectByUfid(id); 
 	}
 

+ 15 - 0
src/main/java/com/goafanti/common/controller/PublicController.java

@@ -31,6 +31,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.socket.TextMessage;
 
 import com.goafanti.admin.service.AdminService;
 import com.goafanti.admin.service.AttachmentService;
@@ -52,6 +53,7 @@ import com.goafanti.common.utils.TimeUtils;
 import com.goafanti.common.utils.VerifyCodeUtils;
 import com.goafanti.common.utils.excel.FileUtils;
 import com.goafanti.core.shiro.token.TokenManager;
+import com.goafanti.core.websocket.SystemWebSocketHandler;
 import com.goafanti.user.service.UserService;
 
 @Controller
@@ -555,6 +557,19 @@ public class PublicController extends CertifyApiController {
 	}
 	
 	
+	/** 省市区查询 **/
+	@RequestMapping(value = "/sendWeb" , method = RequestMethod.POST)
+	@ResponseBody
+	public Result sendWeb(String str){
+		Result res = new Result();
+		SystemWebSocketHandler sys=new SystemWebSocketHandler();
+		TextMessage text=new TextMessage(str.getBytes());
+		sys.sendMessageToUsers(text);
+		res.setData(1);
+		return res;
+	}
+	
+	
     /**
      * 导入流水
      * @param file

+ 0 - 128
src/main/java/com/goafanti/common/controller/WebSocketController.java

@@ -1,128 +0,0 @@
-package com.goafanti.common.controller;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.websocket.OnClose;
-import javax.websocket.OnError;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.PathParam;
-import javax.websocket.server.ServerEndpoint;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.web.socket.server.standard.SpringConfigurator;
-
-@ServerEndpoint(value="/websocketDemo/{userId}",configurator = SpringConfigurator.class)
-public class WebSocketController {
-	//日志记录      
-    private Logger logger = LoggerFactory.getLogger(WebSocketController.class);
-    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
-    private static int onlineCount = 0;
-   
-    //记录每个用户下多个终端的连接
-    private static Map<Long, Set<WebSocketController>> userSocket = new HashMap<>();
- 
-    //需要session来对用户发送数据, 获取连接特征userId
-    private Session session;
-    private Long userId;
-   
-    /**
-     * @Title: onOpen
-     * @Description: websocekt连接建立时的操作
-     * @param @param userId 用户id
-     * @param @param session websocket连接的session属性
-     * @param @throws IOException
-     */
-    @OnOpen
-    public void onOpen(@PathParam("userId") Long userId,Session session) throws IOException{
-        this.session = session;
-        this.userId = userId;
-        onlineCount++;
-        //根据该用户当前是否已经在别的终端登录进行添加操作
-        if (userSocket.containsKey(this.userId)) {
-            logger.debug("当前用户id:{}已有其他终端登录",this.userId);
-            userSocket.get(this.userId).add(this); //增加该用户set中的连接实例
-        }else {
-            logger.debug("当前用户id:{}第一个终端登录",this.userId);
-            Set<WebSocketController> addUserSet = new HashSet<>();
-            addUserSet.add(this);
-            userSocket.put(this.userId, addUserSet);
-        }
-        logger.debug("用户{}登录的终端个数是为{}",userId,userSocket.get(this.userId).size());
-        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
-    }
-   
-    /**
-     * @Title: onClose
-     * @Description: 连接关闭的操作
-     */
-    @OnClose
-    public void onClose(){
-        //移除当前用户终端登录的websocket信息,如果该用户的所有终端都下线了,则删除该用户的记录
-        if (userSocket.get(this.userId).size() == 0) {
-            userSocket.remove(this.userId);
-        }else{
-            userSocket.get(this.userId).remove(this);
-        }
-        logger.debug("用户{}登录的终端个数是为{}",this.userId,userSocket.get(this.userId).size());
-        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
-    }
-   
-    /**
-     * @Title: onMessage
-     * @Description: 收到消息后的操作
-     * @param @param message 收到的消息
-     * @param @param session 该连接的session属性
-     */
-    @OnMessage
-    public void onMessage(String message, Session session) {    
-        logger.debug("收到来自用户id为:{}的消息:{}",this.userId,message);
-        if(session ==null)  logger.debug("session null");
-    }
-   
-    /**
-     * @Title: onError
-     * @Description: 连接发生错误时候的操作
-     * @param @param session 该连接的session
-     * @param @param error 发生的错误
-     */
-    @OnError
-    public void onError(Session session, Throwable error){
-        logger.debug("用户id为:{}的连接发送错误",this.userId);
-        error.printStackTrace();
-    }
-   
-  /**
-   * @Title: sendMessageToUser
-   * @Description: 发送消息给用户下的所有终端
-   * @param @param userId 用户id
-   * @param @param message 发送的消息
-   * @param @return 发送成功返回true,反则返回false
-   */
-    public Boolean sendMessageToUser(Long userId,String message){
-        if (userSocket.containsKey(userId)) {
-            logger.debug(" 给用户id为:{}的所有终端发送消息:{}",userId,message);
-            for (WebSocketController WS : userSocket.get(userId)) {
-                logger.debug("sessionId为:{}",WS.session.getId());
-                try {
-                    WS.session.getBasicRemote().sendText(message);
-                } catch (IOException e) {
-                    e.printStackTrace();
-                    logger.debug(" 给用户id为:{}发送消息失败",userId);
-                    return false;
-                }
-            }
-            return true;
-        }
-        logger.debug("发送错误:当前连接不包含id为:{}的用户",userId);
-        return false;
-    }
-  
-
-}

+ 1 - 0
src/main/java/com/goafanti/common/controller/WebpageController.java

@@ -412,6 +412,7 @@ public class WebpageController extends BaseController {
 	
 	@RequestMapping(value="/portal/websocket")
 	public ModelAndView websocket(HttpServletRequest request, ModelAndView modelview){
+		request.getSession().setAttribute("uid", "con");
 		modelview.setViewName("/portal/websocket");
 		return modelview;
 	}

+ 2 - 0
src/main/java/com/goafanti/common/dao/PublicReleaseMapper.java

@@ -49,4 +49,6 @@ public interface PublicReleaseMapper {
 	void insertSelectiveGetId(PublicRelease in);
 
 	OutPublicRelease selectByUfid(String ufid);
+
+	OutPublicRelease selectByid(Integer id);
 }

+ 11 - 2
src/main/java/com/goafanti/common/mapper/PublicReleaseMapper.xml

@@ -480,12 +480,21 @@ date_format(a.release_end ,'%Y-%m-%d %H:%i:%S') releaseEnds,date_format(a.create
   </select>
   
   <select id="selectByUfid" resultType="com.goafanti.admin.bo.OutPublicRelease">
-  select  a.id,b.nickname ,c.name  aname,date_format(a.release_start,'%Y-%m-%d %H:%i:%S') releaseStarts,a.user_name userName,
-date_format(a.release_end ,'%Y-%m-%d %H:%i:%S') releaseEnds,date_format(a.create_time ,'%Y-%m-%d %H:%i:%S') createTimes,a.status
+  	select  a.id,b.nickname ,c.name  aname,date_format(a.release_start,'%Y-%m-%d %H:%i:%S') releaseStarts,a.user_name userName,
+date_format(a.release_end ,'%Y-%m-%d %H:%i:%S') releaseEnds,date_format(a.create_time ,'%Y-%m-%d %H:%i:%S') createTimes,a.status,
+a.annex_url annexUrl ,a.remarks,a.duration 
 	from public_release a left join `user` b on a.uid =b.id left join admin c on a.aid =c.id
 	where a.ufid= #{id}
   </select>
   
+  <select id="selectByid" resultType="com.goafanti.admin.bo.OutPublicRelease">
+  	select  a.id,b.nickname ,c.name  aname,date_format(a.release_start,'%Y-%m-%d %H:%i:%S') releaseStarts,a.user_name userName,
+date_format(a.release_end ,'%Y-%m-%d %H:%i:%S') releaseEnds,date_format(a.create_time ,'%Y-%m-%d %H:%i:%S') createTimes,a.status,
+a.annex_url annexUrl ,a.remarks,a.duration 
+	from public_release a left join `user` b on a.uid =b.id left join admin c on a.aid =c.id
+	where a.id= #{id}
+  </select>
+  
   <select id="listPublicStatistics" resultType="com.goafanti.admin.bo.OutPublicStatistics">
   	select if(a.status=0,1,0)bh ,if(a.status=1,1,0)wsh,if(a.status=2,1,0)tg,b.name 
   	,sum(if(a.status=2,a.duration,0))duration

+ 0 - 30
src/main/java/com/goafanti/common/service/WSMessageService.java

@@ -1,30 +0,0 @@
-package com.goafanti.common.service;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import com.goafanti.common.utils.WebSocketUtils;
-
-@Service
-public class WSMessageService {
-    private Logger logger = LoggerFactory.getLogger(WSMessageService.class);
-    //声明websocket连接类
-    private WebSocketUtils socket = new WebSocketUtils();
-
-    /**
-     * @Title: sendToAllTerminal
-     * @Description: 调用websocket类给用户下的所有终端发送消息
-     * @param @param userId 用户id
-     * @param @param message 消息
-     * @param @return 发送成功返回true,否则返回false
-     */
-    public Boolean sendToAllTerminal(Long userId,String message){   
-        logger.debug("向用户{}的消息:{}",userId,message);
-        if(socket.sendMessageToUser(userId,message)){
-            return true;
-        }else{
-            return false;
-        }   
-    }           
-}

+ 0 - 128
src/main/java/com/goafanti/common/utils/WebSocketUtils.java

@@ -1,128 +0,0 @@
-package com.goafanti.common.utils;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.websocket.OnClose;
-import javax.websocket.OnError;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.PathParam;
-import javax.websocket.server.ServerEndpoint;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.web.socket.server.standard.SpringConfigurator;
-
-@ServerEndpoint(value="/open/websocket/{userId}",configurator = SpringConfigurator.class)
-public class WebSocketUtils {
-	//日志记录      
-    private Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
-    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
-    private static int onlineCount = 0;
-   
-    //记录每个用户下多个终端的连接
-    private static Map<Long, Set<WebSocketUtils>> userSocket = new HashMap<>();
- 
-    //需要session来对用户发送数据, 获取连接特征userId
-    private Session session;
-    private Long userId;
-   
-    /**
-     * @Title: onOpen
-     * @Description: websocekt连接建立时的操作
-     * @param @param userId 用户id
-     * @param @param session websocket连接的session属性
-     * @param @throws IOException
-     */
-    @OnOpen
-    public void onOpen(@PathParam("userId") Long userId,Session session) throws IOException{
-        this.session = session;
-        this.userId = userId;
-        onlineCount++;
-        //根据该用户当前是否已经在别的终端登录进行添加操作
-        if (userSocket.containsKey(this.userId)) {
-            logger.debug("当前用户id:{}已有其他终端登录",this.userId);
-            userSocket.get(this.userId).add(this); //增加该用户set中的连接实例
-        }else {
-            logger.debug("当前用户id:{}第一个终端登录",this.userId);
-            Set<WebSocketUtils> addUserSet = new HashSet<>();
-            addUserSet.add(this);
-            userSocket.put(this.userId, addUserSet);
-        }
-        logger.debug("用户{}登录的终端个数是为{}",userId,userSocket.get(this.userId).size());
-        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
-    }
-   
-    /**
-     * @Title: onClose
-     * @Description: 连接关闭的操作
-     */
-    @OnClose
-    public void onClose(){
-        //移除当前用户终端登录的websocket信息,如果该用户的所有终端都下线了,则删除该用户的记录
-        if (userSocket.get(this.userId).size() == 0) {
-            userSocket.remove(this.userId);
-        }else{
-            userSocket.get(this.userId).remove(this);
-        }
-        logger.debug("用户{}登录的终端个数是为{}",this.userId,userSocket.get(this.userId).size());
-        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
-    }
-   
-    /**
-     * @Title: onMessage
-     * @Description: 收到消息后的操作
-     * @param @param message 收到的消息
-     * @param @param session 该连接的session属性
-     */
-    @OnMessage
-    public void onMessage(String message, Session session) {    
-        logger.debug("收到来自用户id为:{}的消息:{}",this.userId,message);
-        if(session ==null)  logger.debug("session null");
-    }
-   
-    /**
-     * @Title: onError
-     * @Description: 连接发生错误时候的操作
-     * @param @param session 该连接的session
-     * @param @param error 发生的错误
-     */
-    @OnError
-    public void onError(Session session, Throwable error){
-        logger.debug("用户id为:{}的连接发送错误",this.userId);
-        error.printStackTrace();
-    }
-   
-  /**
-   * @Title: sendMessageToUser
-   * @Description: 发送消息给用户下的所有终端
-   * @param @param userId 用户id
-   * @param @param message 发送的消息
-   * @param @return 发送成功返回true,反则返回false
-   */
-    public Boolean sendMessageToUser(Long userId,String message){
-        if (userSocket.containsKey(userId)) {
-            logger.debug(" 给用户id为:{}的所有终端发送消息:{}",userId,message);
-            for (WebSocketUtils WS : userSocket.get(userId)) {
-                logger.debug("sessionId为:{}",WS.session.getId());
-                try {
-                    WS.session.getBasicRemote().sendText(message);
-                } catch (IOException e) {
-                    e.printStackTrace();
-                    logger.debug(" 给用户id为:{}发送消息失败",userId);
-                    return false;
-                }
-            }
-            return true;
-        }
-        logger.debug("发送错误:当前连接不包含id为:{}的用户",userId);
-        return false;
-    }
-  
-
-}

+ 9 - 6
src/main/java/com/goafanti/core/websocket/SystemWebSocketHandler.java

@@ -4,6 +4,7 @@ import java.io.IOException;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
+import org.springframework.stereotype.Service;
 import org.springframework.web.socket.CloseStatus;
 import org.springframework.web.socket.TextMessage;
 import org.springframework.web.socket.WebSocketHandler;
@@ -12,13 +13,15 @@ import org.springframework.web.socket.WebSocketSession;
 
 import com.goafanti.common.utils.LoggerUtils;
 
+@Service
 public class SystemWebSocketHandler implements WebSocketHandler {
 
-	private static final Map<Long, WebSocketSession> users = new ConcurrentHashMap<>();
+	private static final Map<String, WebSocketSession> users = new ConcurrentHashMap<>();
 
 	@Override
 	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
-		Long userId = (Long) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
+		String userId = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
+		System.out.println("userid="+userId);
 		if (userId != null) {
 			users.put(userId, session);
 			LoggerUtils.debug(getClass(), "添加用户websocket:" + userId);
@@ -36,13 +39,13 @@ public class SystemWebSocketHandler implements WebSocketHandler {
 		if (session.isOpen()) {
 			session.close();
 		}
-		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "关闭");
+		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "error");
 	}
 
 	@SuppressWarnings("unlikely-arg-type")
 	@Override
 	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
-		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "关闭");
+		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "close");
 	}
 
 	@Override
@@ -56,7 +59,7 @@ public class SystemWebSocketHandler implements WebSocketHandler {
 	 * @param message
 	 */
 	public void sendMessageToUsers(TextMessage message) {
-		for (Long userId : users.keySet()) {
+		for (String userId : users.keySet()) {
 			WebSocketSession user = users.get(userId);
 			try {
 				if (user.isOpen()) {
@@ -74,7 +77,7 @@ public class SystemWebSocketHandler implements WebSocketHandler {
 	 * @param userId
 	 * @param message
 	 */
-	public void sendMessageToUser(Long userId, TextMessage message) {
+	public void sendMessageToUser(String userId, TextMessage message) {
 		WebSocketSession user = users.get(userId);
 		if (user != null) {
 			try {

+ 7 - 1
src/main/java/com/goafanti/core/websocket/WebSocketConfig.java

@@ -1,5 +1,6 @@
 package com.goafanti.core.websocket;
 
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@@ -14,11 +15,16 @@ import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
 public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
 	@Autowired
 	SystemWebSocketHandler systemWebSocketHandler;
+	
+	
 
 	@Override
 	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
 		registry.addHandler(systemWebSocketHandler, "/webSocketServer")
-				.addInterceptors(new WebSocketHandshakeInterceptor());
+				.addInterceptors(new WebSocketHandshakeInterceptor())
+				.setAllowedOrigins("*");
+		
+
 
 		registry.addHandler(systemWebSocketHandler, "/sockjs/webSocketServer").setAllowedOrigins("*")
 				.addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS();

+ 5 - 2
src/main/java/com/goafanti/core/websocket/WebSocketHandshakeInterceptor.java

@@ -17,12 +17,15 @@ public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
 	@Override
 	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
 			Map<String, Object> attributes) throws Exception {
+		
 		if (request instanceof ServletServerHttpRequest) {
 			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
 			HttpSession session = servletRequest.getServletRequest().getSession(false);
+			String id = TokenManager.getAdminId();
+			System.out.println("Websocket:用户[ID:" + id + "]握手成功");
 			if (session != null && TokenManager.isLogin()) {
 				// 使用TokenManager.getUserId区分WebSocketHandler,以便定向发送消息
-				attributes.put(Constants.WEBSOCKET_USERNAME, TokenManager.getUserId());
+				attributes.put(Constants.WEBSOCKET_USERNAME, id);
 				return true;
 			}
 		}
@@ -32,6 +35,6 @@ public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
 	@Override
 	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
 			Exception exception) {
-
+		System.out.println("After handshake");
 	}
 }

+ 1 - 1
src/main/resources/applicationContext.xml

@@ -20,5 +20,5 @@
 	<import resource="classpath:spring/spring-shiro.xml" />
 	<import resource="classpath:spring/spring-mvc.xml" />
 	<import resource="classpath:spring/spring-task.xml" />
-
+	<import resource="classpath:spring/spring-websocket.xml" />
 </beans>

+ 8 - 2
src/main/resources/spring/spring-mvc.xml

@@ -10,7 +10,9 @@
 	http://www.springframework.org/schema/task
 	http://www.springframework.org/schema/task/spring-task-4.0.xsd
 	http://www.springframework.org/schema/mvc 
-	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
+	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
+	http://www.springframework.org/schema/websocket
+    http://www.springframework.org/schema/websocket/spring-websocket.xsd">
 
 	<!-- Scan controller -->
 		
@@ -18,6 +20,8 @@
 		base-package="com.goafanti.*.controller;com.goafanti.*.*.controller;com.goafanti.common.task;com.goafanti.common.utils;
 		com.goafanti.core.websocket" />
 		
+		
+	
 
 
 	<bean name="springContextUtils" class="com.goafanti.common.utils.SpringContextUtils" scope="singleton"></bean>
@@ -147,6 +151,8 @@
 	<bean id="shiroFilterUtils" class="com.goafanti.core.shiro.filter.ShiroFilterUtils" scope="singleton">
 		<property name="appName" value="${app.name}" />
 	</bean>
-	<bean id="systemWebSocketHandler" class="com.goafanti.core.websocket.SystemWebSocketHandler" scope="singleton"></bean>
+	
+	
+	
 	
 </beans>

+ 24 - 0
src/main/resources/spring/spring-websocket.xml

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:mvc="http://www.springframework.org/schema/mvc"
+       xmlns:websocket="http://www.springframework.org/schema/websocket"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans.xsd
+        http://www.springframework.org/schema/mvc
+        http://www.springframework.org/schema/mvc/spring-mvc.xsd
+        http://www.springframework.org/schema/websocket
+        http://www.springframework.org/schema/websocket/spring-websocket.xsd">
+        
+    <!--配置 webSocket-->
+    <bean id="systemWebSocketHandler" class="com.goafanti.core.websocket.SystemWebSocketHandler" scope="singleton"></bean>
+    
+    <websocket:handlers allowed-origins="*">
+        <!--指定 webSocket 地址-->
+        <websocket:mapping path="/webSocketServer" handler="systemWebSocketHandler"/>
+        <websocket:handshake-interceptors>
+        	<bean class="com.goafanti.core.websocket.WebSocketHandshakeInterceptor"/>
+        </websocket:handshake-interceptors>
+    </websocket:handlers>
+ 
+</beans>

+ 60 - 59
src/main/webapp/WEB-INF/views/portal/websocket.html

@@ -1,64 +1,65 @@
 <!DOCTYPE html>
-<html>
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
 
-    <head lang="en">
-        <meta charset="UTF-8">
-        <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
-        <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
-        <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
-        <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
-        <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
-        <title>webSocket-用户66</title>
-        <script type="text/javascript">
-            $(function() {
-                var websocket;
-                if('WebSocket' in window) {
-                                        console.log("此浏览器支持websocket");
-                    websocket = new WebSocket("ws://127.0.0.1:8080/open/websocket/66");
-                } else if('MozWebSocket' in window) {
-                    alert("此浏览器只支持MozWebSocket");
-                } else {
-                    alert("此浏览器只支持SockJS");
-                }
-                websocket.onopen = function(evnt) {
-                    $("#tou").html("链接服务器成功!")
-                };
-                websocket.onmessage = function(evnt) {
-                    $("#msg").html($("#msg").html() + "<br/>" + evnt.data);
-                };
-                websocket.onerror = function(evnt) {};
-                websocket.onclose = function(evnt) {
-                    $("#tou").html("与服务器断开了链接!")
-                }
-                $('#send').bind('click', function() {
-                    send();
-                });
 
-                function send() {
-                    if(websocket != null) {
-                        var message = document.getElementById('message').value;
-                        websocket.send(message);
-                    } else {
-                        alert('未与服务器链接.');
-                    }
-                }
-            });
-        </script>
-    </head>
+<head>
+	<style type="text/css">
+		div
+			{
+				border:2px dashed #000000
+			}
+	</style>
 
-    <body>
-        <div class="page-header" id="tou">
-            webSocket多终端聊天测试
-        </div>
-        <div class="well" id="msg"></div>
-        <div class="col-lg">
-            <div class="input-group">
-                <input type="text" class="form-control" placeholder="发送信息..." id="message">
-                <span class="input-group-btn">
-                    <button class="btn btn-default" type="button" id="send" >发送</button>
-                </span>
-            </div>
-        </div>
-    </body>
+	<script type="text/javascript">
 
-</html>
+	</script>
+</head>
+
+<body>
+	<h1>Rumia chat room</h1>
+	
+	<div>
+		<p id="talked"></p>
+	</div>
+	<br>
+	<div>
+		<input type="text" id="say">
+		<button onclick="sendData()">SAY</button>
+	</div>
+	
+	
+
+	<script type="text/javascript">
+
+		var ws = new WebSocket("ws://" + window.location.host + "/webSocketServer");
+
+		function sendData()
+		{
+			var msg = document.getElementById("say").value;
+			ws.send(msg);
+		}
+
+		ws.onopen = function(evt)
+		{ 
+			console.log("Connection open ..."); 
+		};
+
+		ws.onmessage = function(evt)
+		{
+			console.log("Received Message: " + evt.data);
+			document.getElementById("talked").innerHTML = document.getElementById("talked").innerHTML + "<br>" + evt.data;
+		};
+
+		ws.onclose = function(evt)
+		{
+			console.log("Connection closed.");
+		};
+
+		ws.onerror = function(evt)
+		{
+			console.log("error!!!"); 
+		};
+
+	</script>
+
+</body>