Browse Source

初始化

master
VIVIMAN 3 years ago
commit
ff75951858
  1. 8
      .gitignore
  2. 25
      .myhibernatedata
  3. 13
      .mymetadata
  4. 8
      README.md
  5. 3
      WebRoot/META-INF/MANIFEST.MF
  6. 28
      WebRoot/WEB-INF/classes/applicationContext.xml
  7. BIN
      WebRoot/WEB-INF/classes/com/he/Test.class
  8. BIN
      WebRoot/WEB-INF/classes/com/he/entity/Message.class
  9. BIN
      WebRoot/WEB-INF/classes/com/he/websocket/MyHandShake.class
  10. BIN
      WebRoot/WEB-INF/classes/com/he/websocket/WebsocketConfig.class
  11. BIN
      WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler$1.class
  12. BIN
      WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler$2.class
  13. BIN
      WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler.class
  14. 16
      WebRoot/WEB-INF/classes/log4j.properties
  15. BIN
      WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar
  16. 2270
      WebRoot/WEB-INF/spring-form.tld
  17. 457
      WebRoot/WEB-INF/spring.tld
  18. 68
      WebRoot/WEB-INF/web.xml
  19. 34
      WebRoot/log.html
  20. 9555
      WebRoot/resources/jquery.js
  21. 371
      pom.xml
  22. 28
      src/applicationContext.xml
  23. 44
      src/com/he/Test.java
  24. 63
      src/com/he/entity/Message.java
  25. 61
      src/com/he/websocket/MyHandShake.java
  26. 30
      src/com/he/websocket/WebsocketConfig.java
  27. 322
      src/com/he/websocket/WebsocketHandler.java
  28. 16
      src/log4j.properties

8
.gitignore

@ -0,0 +1,8 @@
/.classpath
/.project
/.springBeans
/.settings/
/.idea/
/target/
ChenSheng.iml
springWebsockeForTomcatLog.iml

25
.myhibernatedata

@ -0,0 +1,25 @@
#MyEclipse Hibernate Properties
#Mon Mar 14 16:36:19 GMT+08:00 2016
sessionFactoryName=
genBasicCompId=false
profile=
daoSFId=
version=3.3
jndiPath=
detectM2M=false
reStrategyClass=
detectO2O=false
springDaoFile=
useJavaTypes=true
keyGenerator=
libInstallFolder=WebRoot/WEB-INF/lib
addLibs2Project=true
genVersionTag=false
sessionFactoryId=sessionFactory
basePersistenceClass=
genAnnotations=false
reSettingsFile=
configFile=/ChenSheng/src/applicationContext.xml
createConfigFile=false
addLibs2Classpath=true
baseDaoClass=

13
.mymetadata

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-module
type="WEB"
name="spirngWebsocket"
id="myeclipse.1457944315708"
context-root="/ChenSheng"
j2ee-spec="5.0"
archive="spirngWebsocket.war">
<attributes>
<attribute name="webrootdir" value="WebRoot" />
</attributes>
</project-module>

8
README.md

@ -0,0 +1,8 @@
# springWebsockeForTomcatLog
相比于原始博客http://blog.csdn.net/smile326/article/details/52218264
文中的内容,主要作以下两点改变
1.为了在建立连接之后能够获取到上传的参数,用MyHandShake实现了HandshakeInterceptor接口,在beforeHandshake方法里面对上传参数进行了处理,所以后面才可以获取到。
2.session的容器,使用ConcurrentHashMap,保证线程的足够安全。
用一个简单的servlet类test,模拟接口,部署之后访问test,即可看到test接口中打印的内容出现在log.html的页面上

3
WebRoot/META-INF/MANIFEST.MF

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

28
WebRoot/WEB-INF/classes/applicationContext.xml

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<!-- websocket配置1 -->
<bean id="websocket" class="com.he.websocket.WebsocketHandler" />
<websocket:handlers>
<websocket:mapping path="/ws.do" handler="websocket" />
<websocket:handshake-interceptors>
<bean class="com.he.websocket.MyHandShake" />
</websocket:handshake-interceptors>
</websocket:handlers>
<context:component-scan base-package="com.he.websocket.WebsocketConfig" />
<context:component-scan base-package="com.he.websocket.WebsocketHandler" />
</beans>

BIN
WebRoot/WEB-INF/classes/com/he/Test.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/entity/Message.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/websocket/MyHandShake.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/websocket/WebsocketConfig.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler$1.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler$2.class

Binary file not shown.

BIN
WebRoot/WEB-INF/classes/com/he/websocket/WebsocketHandler.class

Binary file not shown.

16
WebRoot/WEB-INF/classes/log4j.properties

@ -0,0 +1,16 @@
log4j.rootLogger=DEBUG,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold=WARN
log4j.appender.stdout.layout.ConversionPattern = [%-5p] [%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%x] %c %l - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p] [%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%X{ip}] %c %l - %m%n
log4j.appender.logfile.Threshold = WARN
log4j.appender.logfile.append=true
log4j.appender.logfile.MaxFileSize=1024KB
log4j.appender.logfile.MaxBackupIndex=50
log4j.appender.logfile.File = C:/log/project.log

BIN
WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar

Binary file not shown.

2270
WebRoot/WEB-INF/spring-form.tld

File diff suppressed because it is too large

457
WebRoot/WEB-INF/spring.tld

@ -0,0 +1,457 @@
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>Spring Framework JSP Tag Library</description>
<tlib-version>3.0</tlib-version>
<short-name>spring</short-name>
<uri>http://www.springframework.org/tags</uri>
<tag>
<description>
Sets default HTML escape value for the current page.
Overrides a "defaultHtmlEscape" context-param in web.xml, if any.
</description>
<name>htmlEscape</name>
<tag-class>org.springframework.web.servlet.tags.HtmlEscapeTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>Set the default value for HTML escaping, to be put
into the current PageContext.</description>
<name>defaultHtmlEscape</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Escapes its enclosed body content, applying HTML escaping and/or JavaScript escaping.
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
</description>
<name>escapeBody</name>
<tag-class>org.springframework.web.servlet.tags.EscapeBodyTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>Set HTML escaping for this tag, as boolean value. Overrides the
default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set JavaScript escaping for this tag, as boolean value.
Default is false.</description>
<name>javaScriptEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Retrieves the message with the given code, or text if code isn't resolvable.
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
</description>
<name>message</name>
<tag-class>org.springframework.web.servlet.tags.MessageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>A MessageSourceResolvable argument (direct or through JSP EL).
Fits nicely when used in conjunction with Spring's own validation error
classes which all implement the MessageSourceResolvable interface. For
example, this allows you to iterate over all of the errors in a form,
passing each error (using a runtime expression) as the value of this
'message' attribute, thus effecting the easy display of such error
messages.</description>
<name>message</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The code (key) to use when looking up the message.
If code is not provided, the text attribute will be used.</description>
<name>code</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set optional message arguments for this tag, as a
(comma-)delimited String (each String argument can contain JSP EL),
an Object array (used as argument array), or a single Object (used
as single argument).</description>
<name>arguments</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The separator character to be used for splitting the
arguments string value; defaults to a 'comma' (',').</description>
<name>argumentSeparator</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Default text to output when a message for the given code
could not be found. If both text and code are not set, the tag will
output null.</description>
<name>text</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The string to use when binding the result to the page,
request, session or application scope. If not specified, the result
gets outputted to the writer (i.e. typically directly to the JSP).</description>
<name>var</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The scope to use when exporting the result to a variable.
This attribute is only used when var is also set. Possible values are
page, request, session and application.</description>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as boolean value.
Overrides the default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set JavaScript escaping for this tag, as boolean value. Default is false.</description>
<name>javaScriptEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Retrieves the theme message with the given code, or text if code isn't resolvable.
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
</description>
<name>theme</name>
<tag-class>org.springframework.web.servlet.tags.ThemeTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>A MessageSourceResolvable argument (direct or through JSP EL).</description>
<name>message</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The code (key) to use when looking up the message.
If code is not provided, the text attribute will be used.</description>
<name>code</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set optional message arguments for this tag, as a
(comma-)delimited String (each String argument can contain JSP EL),
an Object array (used as argument array), or a single Object (used
as single argument).</description>
<name>arguments</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The separator character to be used for splitting the
arguments string value; defaults to a 'comma' (',').</description>
<name>argumentSeparator</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Default text to output when a message for the given code
could not be found. If both text and code are not set, the tag will
output null.</description>
<name>text</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The string to use when binding the result to the page,
request, session or application scope. If not specified, the result
gets outputted to the writer (i.e. typically directly to the JSP).</description>
<name>var</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The scope to use when exporting the result to a variable.
This attribute is only used when var is also set. Possible values are
page, request, session and application.</description>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as boolean value.
Overrides the default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set JavaScript escaping for this tag, as boolean value. Default is false.</description>
<name>javaScriptEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Provides Errors instance in case of bind errors.
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
</description>
<name>hasBindErrors</name>
<tag-class>org.springframework.web.servlet.tags.BindErrorsTag</tag-class>
<body-content>JSP</body-content>
<variable>
<name-given>errors</name-given>
<variable-class>org.springframework.validation.Errors</variable-class>
</variable>
<attribute>
<description>The name of the bean in the request, that needs to be
inspected for errors. If errors are available for this bean, they
will be bound under the 'errors' key.</description>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as boolean value.
Overrides the default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Sets a nested path to be used by the bind tag's path.
</description>
<name>nestedPath</name>
<tag-class>org.springframework.web.servlet.tags.NestedPathTag</tag-class>
<body-content>JSP</body-content>
<variable>
<name-given>nestedPath</name-given>
<variable-class>java.lang.String</variable-class>
</variable>
<attribute>
<description>Set the path that this tag should apply. E.g. 'customer'
to allow bind paths like 'address.street' rather than
'customer.address.street'.</description>
<name>path</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Provides BindStatus object for the given bind path.
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
</description>
<name>bind</name>
<tag-class>org.springframework.web.servlet.tags.BindTag</tag-class>
<body-content>JSP</body-content>
<variable>
<name-given>status</name-given>
<variable-class>org.springframework.web.servlet.support.BindStatus</variable-class>
</variable>
<attribute>
<description>The path to the bean or bean property to bind status
information for. For instance account.name, company.address.zipCode
or just employee. The status object will exported to the page scope,
specifically for this bean or bean property</description>
<name>path</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set whether to ignore a nested path, if any. Default is to not ignore.</description>
<name>ignoreNestedPath</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as boolean value. Overrides
the default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>
Provides transformation of variables to Strings, using an appropriate
custom PropertyEditor from BindTag (can only be used inside BindTag).
The HTML escaping flag participates in a page-wide or application-wide setting
(i.e. by HtmlEscapeTag or a 'defaultHtmlEscape' context-param in web.xml).
</description>
<name>transform</name>
<tag-class>org.springframework.web.servlet.tags.TransformTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>The value to transform. This is the actual object you want
to have transformed (for instance a Date). Using the PropertyEditor that
is currently in use by the 'spring:bind' tag.</description>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The string to use when binding the result to the page,
request, session or application scope. If not specified, the result gets
outputted to the writer (i.e. typically directly to the JSP).</description>
<name>var</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The scope to use when exported the result to a variable.
This attribute is only used when var is also set. Possible values are
page, request, session and application.</description>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as boolean value. Overrides
the default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>URL tag based on the JSTL c:url tag. This variant is fully
backwards compatible with the standard tag. Enhancements include support
for URL template parameters.</description>
<name>url</name>
<tag-class>org.springframework.web.servlet.tags.UrlTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>The URL to build. This value can include template place holders
that are replaced with the URL encoded value of the named parameter. Parameters
must be defined using the param tag inside the body of this tag.</description>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Specifies a remote application context path. The default is the
current application context path.</description>
<name>context</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The name of the variable to export the URL value to.</description>
<name>var</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The scope for the var. 'application', 'session', 'request' and
'page' scopes are supported. Defaults to page scope. This attribute has no
effect unless the var attribute is also defined.</description>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as a boolean value. Overrides the
default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set JavaScript escaping for this tag, as a boolean value.
Default is false.</description>
<name>javaScriptEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>Parameter tag based on the JSTL c:param tag. The sole purpose is to
support params inside the spring:url tag.</description>
<name>param</name>
<tag-class>org.springframework.web.servlet.tags.ParamTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>The name of the parameter.</description>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The value of the parameter.</description>
<name>value</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<description>Evaluates a Spring expression (SpEL) and either prints the result or assigns it to a variable.</description>
<name>eval</name>
<tag-class>org.springframework.web.servlet.tags.EvalTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<description>The expression to evaluate.</description>
<name>expression</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The name of the variable to export the evaluation result to.</description>
<name>var</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>The scope for the var. 'application', 'session', 'request' and
'page' scopes are supported. Defaults to page scope. This attribute has no
effect unless the var attribute is also defined.</description>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set HTML escaping for this tag, as a boolean value. Overrides the
default HTML escaping setting for the current page.</description>
<name>htmlEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Set JavaScript escaping for this tag, as a boolean value. Default is false.</description>
<name>javaScriptEscape</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

68
WebRoot/WEB-INF/web.xml

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Spring -->
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring 刷新Introspector防止内存泄露 -->
<!-- <listener>-->
<!--
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
-->
<!-- </listener>-->
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.he.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

34
WebRoot/log.html

@ -0,0 +1,34 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tail log</title>
<script src="//cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
<style>
html,body
{
height:100%;
width:100%;
}
</style>
</head>
<body>
<div id="log-container" style="height: 100%; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;">
<div>
</div>
</div>
</body>
<script>
$(document).ready(function() {
// 指定websocket路径
var websocket = new WebSocket('ws://localhost:8080/w/ws.do');
websocket.onmessage = function(event) {
// 接收服务端的实时日志并添加到HTML页面中
$("#log-container div").append(event.data + "<p> </p>");
// 滚动条滚动到最低部
$("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
};
});
</script>
</body>
</html>

9555
WebRoot/resources/jquery.js

File diff suppressed because it is too large

371
pom.xml

@ -0,0 +1,371 @@
<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>
<groupId>ChenSheng</groupId>
<artifactId>ChenSheng</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name/>
<description/>
<dependencies>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>5.0-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument-tomcat</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>jotm</groupId>
<artifactId>jotm</artifactId>
<version>2.0.10</version>
</dependency>
<dependency>
<groupId>com.experlog</groupId>
<artifactId>xapool</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.lang</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>com.springsource.org.junit</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>easymock</groupId>
<artifactId>easymock</artifactId>
<version>1.2_Java1.5</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>wstx-asl</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.21</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>com.springsource.javax.inject</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>com.springsource.org.codehaus.jackson.mapper</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>3.0.1.RELEASE-A</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>3.0.1.RELEASE-A</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-struts</artifactId>
<version>3.0.1.RELEASE-A</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.1.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>3.1.0.GA</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.9.0.GA</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.6</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src</sourceDirectory>
<outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${basedir}/WebRoot</webappDirectory>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

28
src/applicationContext.xml

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<!-- websocket配置1 -->
<bean id="websocket" class="com.he.websocket.WebsocketHandler" />
<websocket:handlers>
<websocket:mapping path="/ws.do" handler="websocket" />
<websocket:handshake-interceptors>
<bean class="com.he.websocket.MyHandShake" />
</websocket:handshake-interceptors>
</websocket:handlers>
<context:component-scan base-package="com.he.websocket.WebsocketConfig" />
<context:component-scan base-package="com.he.websocket.WebsocketHandler" />
</beans>

44
src/com/he/Test.java

@ -0,0 +1,44 @@
package com.he;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.socket.TextMessage;
import com.google.gson.GsonBuilder;
import com.he.websocket.WebsocketHandler;
public class Test extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static final Logger LOG = Logger.getLogger(Test.class);
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/json;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
try {
WebsocketHandler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson("·ÃÎÊtest½Ó¿Ú\\n")));
LOG.warn("=========test=========");
System.out.println("syso ================test==============");
out.println("=====================test==========================");
out.flush();
out.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

63
src/com/he/entity/Message.java

@ -0,0 +1,63 @@
package com.he.entity;
import java.util.Date;
/**
*@function消息类
*@date2016-9-27 上午09:49:55
*@author:Administrator.
*@notice
*/
public class Message {
//发送者
public String from;
//发送者名称
public String fromName;
//接收者
public String to;
//发送的文本
public String text;
//发送日期
public Date date;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

61
src/com/he/websocket/MyHandShake.java

@ -0,0 +1,61 @@
package com.he.websocket;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
/**
*@function实现获取上传的参数然后设置到socke 的session中
*@parameter:
*@return
*@date2016-9-10 上午11:15:03
*@author:Administrator
*@notice:
*/
public class MyHandShake implements HandshakeInterceptor{
protected static final Logger LOG = Logger.getLogger(MyHandShake.class);
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
}
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
try {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
// 标记用户
String uid = servletRequest.getServletRequest().getParameter("uid");
LOG.warn("servlet request uid is :" + uid);
if (uid != null) {
attributes.put("uid", uid);
} else {
return false;
}
}
LOG.info("websocket handshake success");
return true;
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn(sw.toString());
LOG.warn("websocket 的handshake出现异常");
return false;
}
}
}

30
src/com/he/websocket/WebsocketConfig.java

@ -0,0 +1,30 @@
package com.he.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* WebScoketÅäÖô¦ÀíÆ÷
* @author he
* @Date 2016Äê03ÔÂ15ÈÕ ÏÂÎç1:15:09
*/
@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/ws").addInterceptors(new MyHandShake());
registry.addHandler(myHandler(), "/ws/sockjs").addInterceptors(new MyHandShake()).withSockJS();
}
@Bean
public WebsocketHandler myHandler() {
return new WebsocketHandler();
}
}

322
src/com/he/websocket/WebsocketHandler.java

@ -0,0 +1,322 @@
package com.he.websocket;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.he.entity.Message;
/**
*@functionsocket处理器
*@date2016-9-27 上午09:48:31
*@author:He.
*@notice
*/
@Component
public class WebsocketHandler extends TextWebSocketHandler {
private final static Logger LOG = Logger.getLogger(WebsocketHandler.class);
public static ConcurrentHashMap<String, WebSocketSession> websocketSessionsConcurrentHashMap;
public static ConcurrentHashMap<String, WebSocketSession> websocketSessionsConcurrentHashMapForLog;
static {
websocketSessionsConcurrentHashMap = new ConcurrentHashMap<String, WebSocketSession>();
websocketSessionsConcurrentHashMapForLog = new ConcurrentHashMap<String, WebSocketSession>();
}
/**
* 建立连接后
*/
public void afterConnectionEstablished(WebSocketSession session) {
try {
String uid = (String) session.getAttributes().get("uid");
if (!(uid == null)) {
if (uid.equals("log")) {
if (websocketSessionsConcurrentHashMapForLog.get(uid) == null) {
websocketSessionsConcurrentHashMapForLog.put(uid + Math.random(), session);
} else {
websocketSessionsConcurrentHashMapForLog.get(uid).close();
websocketSessionsConcurrentHashMapForLog.put(uid + Math.random(), session);
}
} else {
if (websocketSessionsConcurrentHashMap.get(uid) == null) {
websocketSessionsConcurrentHashMap.put(uid, session);
} else {
websocketSessionsConcurrentHashMap.get(uid).close();
websocketSessionsConcurrentHashMap.put(uid, session);
}
}
}
LOG.warn("======websocket建立连接完成======");
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("afterConnectionEstablished出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
* 消息处理在客户端通过Websocket API发送的消息会经过这里然后进行相应的处理
*/
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
try {
if (message.getPayloadLength() == 0)
return;
Message msg = new Gson().fromJson(message.getPayload().toString(), Message.class);
msg.setDate(new Date());
sendMessageToUser(msg.getTo(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
LOG.warn("======websocket消息处理完成======");
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("handleMessage出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
* 消息传输错误处理
*/
public void handleTransportError(WebSocketSession session, Throwable exception) {
try {
if (session.isOpen()) {
session.close();
}
Iterator<Entry<String, WebSocketSession>> it = websocketSessionsConcurrentHashMap.entrySet().iterator();
LOG.warn("======websocket消息传输错误======");
// 移除Socket会话
while (it.hasNext()) {
Entry<String, WebSocketSession> entry = it.next();
if (entry.getValue().getId().equals(session.getId())) {
websocketSessionsConcurrentHashMap.remove(entry.getKey());
System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
break;
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("handleTransportError出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
* 关闭连接后
*/
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
try {
LOG.warn("Websocket:" + session.getId() + "已经关闭");
Iterator<Entry<String, WebSocketSession>> it = websocketSessionsConcurrentHashMap.entrySet().iterator();
// 移除Socket会话
LOG.warn("======websocket关闭连接完成======");
while (it.hasNext()) {
Entry<String, WebSocketSession> entry = it.next();
if (entry.getValue().getId().equals(session.getId())) {
websocketSessionsConcurrentHashMap.remove(entry.getKey());
System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
break;
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("afterConnectionClosed出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
public boolean supportsPartialMessages() {
return false;
}
/**
* 给所有在线用户发送消息
*
* @param message
* @throws IOException
*/
public static void broadcast(final TextMessage message) {
try {
Iterator<Entry<String, WebSocketSession>> it = websocketSessionsConcurrentHashMap.entrySet().iterator();
LOG.info("======websocket群发======");
// 多线程群发
while (it.hasNext()) {
final Entry<String, WebSocketSession> entry = it.next();
if (entry.getValue().isOpen()) {
// entry.getValue().sendMessage(message);
new Thread(new Runnable() {
public void run() {
try {
if (entry.getValue().isOpen()) {
entry.getValue().sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("broadcast出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
* 给某个用户发送消息
*
* @param userName
* @param message
* @throws IOException
*/
public static void sendMessageToUser(Object uid, TextMessage message) {
try {
WebSocketSession session = websocketSessionsConcurrentHashMap.get(uid);
LOG.warn("======websocket给某个用户发送消息======");
if (session != null && session.isOpen()) {
session.sendMessage(message);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("send message to user出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
public static void sendMessageToUser(Object uid, String message) {
try {
WebSocketSession session = websocketSessionsConcurrentHashMap.get(uid);
if (session != null && session.isOpen()) {
LOG.warn("======websocket给某个用户发送消息======");
session.sendMessage(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(message)));
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("send message to user出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
*@function广播日志log
*@parameter:
*@return
*@date2016-8-5 上午10:28:01
*@author:Administrator
* @return
*@notice:
*/
public static void broadcastLog(final String log) {
try {
Iterator<Entry<String, WebSocketSession>> it = websocketSessionsConcurrentHashMapForLog.entrySet().iterator();
// LOG.warn("开始websocket群发:" + log);
// 多线程群发
while (it.hasNext()) {
final Entry<String, WebSocketSession> entry = it.next();
Object uid = entry.getKey();
WebSocketSession session = websocketSessionsConcurrentHashMapForLog.get(uid);
if (session !=null && session.isOpen()) {
session.sendMessage(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(log)));
LOG.warn("完成websocket群发日志");
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("广播log出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
/**
*@function向不同的map广播
*@parameter:
*@return
*@date2016-8-5 上午11:25:38
*@author:Administrator
*@notice:
*/
public static void broadcast(ConcurrentHashMap<String, WebSocketSession> hashMap, final String message) {
try {
Iterator<Entry<String, WebSocketSession>> it = hashMap.entrySet().iterator();
LOG.warn("=======websocket群发======");
// 多线程群发
while (it.hasNext()) {
final Entry<String, WebSocketSession> entry = it.next();
if (entry.getValue().isOpen()) {
// entry.getValue().sendMessage(message);
new Thread(new Runnable() {
public void run() {
if (entry.getValue().isOpen()) {
sendMessageToUser(entry.getValue(), message);
}
}
}).start();
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOG.warn("广播log出现异常");
LOG.warn(sw.toString());
e.printStackTrace();
}
}
}

16
src/log4j.properties

@ -0,0 +1,16 @@
log4j.rootLogger=DEBUG,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold=WARN
log4j.appender.stdout.layout.ConversionPattern = [%-5p] [%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%x] %c %l - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p] [%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%X{ip}] %c %l - %m%n
log4j.appender.logfile.Threshold = WARN
log4j.appender.logfile.append=true
log4j.appender.logfile.MaxFileSize=1024KB
log4j.appender.logfile.MaxBackupIndex=50
log4j.appender.logfile.File = C:/log/project.log
Loading…
Cancel
Save