diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 9cc84ea..0000000 Binary files a/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 6c8c0e0..0000000 --- a/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/README.md b/README.md index da3b9b3..684d80f 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,32 @@ -# InChat(当前版本1.6.0) +# InChat-IM-API(当前版本0.0.2) ## 简介 ->(InChat)Iot Netty Chat +本项目为InChat核心项目,服务端项目,以API形式作为对外功能,类似腾讯IM的服务端作用,本文也将着重讲解本项目的各个API,目前还没有嵌入Iot通信模块,仅以WebSocket的聊天室作为初期发展,需要使用到Iot的朋友可以先去[Master](https://github.com/UncleCatMySelf/InChat/tree/master)项目了解。 -仿微信聊天应用,一步一步更新,基于SpringBoot-WebSocket通用框架,结合Netty进行聊天社交,并记录聊天日志, -异步存储,前端暂用SUI Mobile,添加实现TCP/IP后端通信端口(MQTT协议、可实时与单片机等TCP硬件通信)、加入图片处理流, -聊天实现文字与图片发送功能、API调用Netty长链接执行发送消息(在线数、用户列表) +## swagger-ui -## 基本架构图(1.5.2版) +前端对接公告,目前推出API,请均已此文档说明的为主,其余API非正式版或测试版,误用 +查看API列表 +> http://localhost:8080/susu/swagger-ui.html -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/ggg1.png) +## API列表详情 -## 功能 +* 1、账号注册 +> POST http://loclhost:8080/susu/user/to_register +- 参数:username(用户名) +- 参数:password(密码) +- 前端Tip:传值判断,参数均不能为空,密码限制在前端做判断 ->实时聊天 ->异步CRUD处理消息日志 ->获取聊天历史 ->用户登录、记录登录用户聊天历史 ->防止二次登录 ->SUI Mobile仿微信样式 ->TCP/IP软硬件通信(8092) ->MQTT协议下的Iot物联网通信(8094) ->图片发送聊天功能 ->API调用Netty长链接执行发送消息(在线用户数、用户列表) ->下版(1.7.0):好友功能等 -## 版本迭代介绍 +## 返回码与信息值 -* 1.0.0版本 +| 返回码 | 信息内容 | 备注 | +|------|---------|------| +| 200 | 成功 | | +| 555 | 参数错误| | +| 556 | 用户名存在| | -用户登录,聊天历史,随机用户名,异步数据写入:https://segmentfault.com/a/1190000016615063 +## 提示 -* 1.2.0版本 - -修复聊天记录功能,实现重复信息录入,完善前端页面,回车监听等:https://segmentfault.com/a/1190000016637814 - -* 1.3.0版本 - -用户注册登录功能,系统聊天绑定用户,禁止二次登录等,前端页面大改 - -* 1.4.1版本 - -本人主导SUI Mobile构建仿微信样式页面版,使用时开F12手机界面 - -* 1.5.2版本 - -TCP/IP软硬件通信-单片机等应用的TCP通信,Netty处理二进制图片发送聊天功能 - -* 1.5.8版本 - -MQTT协议软硬件通信等,Iot物联网 - -* 1.6.0版本 - -API调用Netty长链接执行发送消息(在线数、用户列表):https://segmentfault.com/a/1190000016603392 - - -## 配置 - ->application.yml 数据库配置、Netty参数配置 - ->TCP需先去com.myself.nettychat.tcptest包下执行CRC16myself获取发送数据, - ->再执行TCPTestClient发送数据,请勿随意更改发送格式(通信协议来的) - ->http://localhost:8080/susu/admin/loginsui 启动访问路径 - ->mqtt协议测试在mqttclient包下 - ->http://localhost:8080/susu/swagger-ui.html 查看API文档 - -## 效果图 - -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/001%20(5).png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/001%20(3).png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/001%20(4).png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/001%20(2).png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/001%20(1).png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/9.png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/10.png) -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/nettychat/11.png) - -## 预留BUG - -``` -io.netty.handler.codec.CorruptedFrameException: Max frame length of 65536 has been exceeded. -图片过大,需要在前端做图片上传压缩 - -Uncaught TypeError: msg.substring is not a function at WebSocket.socket.onmessage (newChat.js:38) -前端代码的一点问题,不影响项目正常运行 - -java.io.IOException: 远程主机强迫关闭了一个现有的连接。 -TCP客户端连接主动关闭,不影响,良性报错 -``` - -## 下载地址 - -下载地址:https://github.com/UncleCatMySelf/SBToNettyChat/releases - -## 交流与提问 - -提问与Bug上报:https://github.com/UncleCatMySelf/SBToNettyChat/issues - -QQ群:628793702(仅供交流,不提供问题解答) - -## 关于作者 - -个人公众号:UncleCatMySelf - -![Image text](https://raw.githubusercontent.com/UncleCatMySelf/img-myself/master/img/%E5%85%AC%E4%BC%97%E5%8F%B7.png) +仅API列表详情中的API处于可用状态,其余API请勿使用,暂未基本完成,使用请详看文档 \ No newline at end of file diff --git a/h5/chat.html b/h5/chat.html deleted file mode 100644 index 91d15b2..0000000 --- a/h5/chat.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - - WebSocket Chat - - - - -
-

SpringBoot netty 聊天室

- -
- - -
-
-
- - \ No newline at end of file diff --git a/h5/home.html b/h5/home.html deleted file mode 100644 index 541e6b7..0000000 --- a/h5/home.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - 酥酥 - - - - - - - - - - -
-
-

酥酥

-
- -
- -
-
- - - - - \ No newline at end of file diff --git a/h5/index.html b/h5/index.html deleted file mode 100644 index 32e88ea..0000000 --- a/h5/index.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - 酥酥 - - - - - - - - - - -
-
- -
-

登录

-
-
-
-
    - -
  • -
    -
    -
    -
    账号
    -
    - -
    -
    -
    -
  • -
  • -
    -
    -
    -
    密码
    -
    - -
    -
    -
    -
  • -
-
-
-
- - -
-
-
- -
-
- - - - - - - \ No newline at end of file diff --git a/h5/logoSmall.png b/h5/logoSmall.png deleted file mode 100644 index 08b5d51..0000000 Binary files a/h5/logoSmall.png and /dev/null differ diff --git a/mqttclient/mqttclient/.gitignore b/mqttclient/mqttclient/.gitignore deleted file mode 100644 index 82eca33..0000000 --- a/mqttclient/mqttclient/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/build/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ \ No newline at end of file diff --git a/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.jar b/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 9cc84ea..0000000 Binary files a/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.properties b/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 6c8c0e0..0000000 --- a/mqttclient/mqttclient/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/mqttclient/mqttclient/mvnw b/mqttclient/mqttclient/mvnw deleted file mode 100644 index 5bf251c..0000000 --- a/mqttclient/mqttclient/mvnw +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mqttclient/mqttclient/mvnw.cmd b/mqttclient/mqttclient/mvnw.cmd deleted file mode 100644 index 019bd74..0000000 --- a/mqttclient/mqttclient/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/mqttclient/mqttclient/pom.xml b/mqttclient/mqttclient/pom.xml deleted file mode 100644 index 2d1b502..0000000 --- a/mqttclient/mqttclient/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - - com.myself - mqttclient - 0.0.1-SNAPSHOT - jar - - mqttclient - Demo project for Spring Boot - - - org.springframework.boot - spring-boot-starter-parent - 2.0.5.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/mqttclient/mqttclient/src/main/java/com/myself/mqttclient/MqttclientApplication.java b/mqttclient/mqttclient/src/main/java/com/myself/mqttclient/MqttclientApplication.java deleted file mode 100644 index 569cf76..0000000 --- a/mqttclient/mqttclient/src/main/java/com/myself/mqttclient/MqttclientApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.myself.mqttclient; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MqttclientApplication { - - public static void main(String[] args) { - SpringApplication.run(MqttclientApplication.class, args); - } -} diff --git a/mqttclient/mqttclient/src/main/resources/application.properties b/mqttclient/mqttclient/src/main/resources/application.properties deleted file mode 100644 index e69de29..0000000 diff --git a/mqttclient/mqttclient/src/test/java/com/myself/mqttclient/MqttclientApplicationTests.java b/mqttclient/mqttclient/src/test/java/com/myself/mqttclient/MqttclientApplicationTests.java deleted file mode 100644 index 5c938a0..0000000 --- a/mqttclient/mqttclient/src/test/java/com/myself/mqttclient/MqttclientApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.myself.mqttclient; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class MqttclientApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/mvnw b/mvnw deleted file mode 100644 index 5bf251c..0000000 --- a/mvnw +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index 019bd74..0000000 --- a/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/src/main/java/com/myself/nettychat/DefaultAutoService.java b/src/main/java/com/myself/nettychat/DefaultAutoService.java deleted file mode 100644 index e4b4cc7..0000000 --- a/src/main/java/com/myself/nettychat/DefaultAutoService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.myself.nettychat; - -import com.myself.nettychat.bootstrap.BaseAuthService; -import org.springframework.stereotype.Service; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 默认权限 - **/ -@Service -public class DefaultAutoService implements BaseAuthService { - - @Override - public boolean authorized(String username, String password) { - return true; - } -} diff --git a/src/main/java/com/myself/nettychat/auto/InitServer.java b/src/main/java/com/myself/nettychat/auto/InitServer.java deleted file mode 100644 index 3729fc3..0000000 --- a/src/main/java/com/myself/nettychat/auto/InitServer.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.myself.nettychat.auto; - - -import com.myself.nettychat.bootstrap.BootstrapServer; -import com.myself.nettychat.bootstrap.NettyBootstrapServer; -import com.myself.nettychat.common.properties.InitNetty; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 初始化服务 - **/ -public class InitServer { - - private InitNetty serverBean; - - public InitServer(InitNetty serverBean) { - this.serverBean = serverBean; - } - - BootstrapServer bootstrapServer; - - public void open(){ - if(serverBean!=null){ - bootstrapServer = new NettyBootstrapServer(); - bootstrapServer.setServerBean(serverBean); - bootstrapServer.start(); - } - } - - - public void close(){ - if(bootstrapServer!=null){ - bootstrapServer.shutdown(); - } - } - -} diff --git a/src/main/java/com/myself/nettychat/auto/ServerAutoConfigure.java b/src/main/java/com/myself/nettychat/auto/ServerAutoConfigure.java deleted file mode 100644 index 961e458..0000000 --- a/src/main/java/com/myself/nettychat/auto/ServerAutoConfigure.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.myself.nettychat.auto; - -import com.myself.nettychat.bootstrap.scan.SacnScheduled; -import com.myself.nettychat.bootstrap.scan.ScanRunnable; -import com.myself.nettychat.common.enums.ProtocolEnum; -import com.myself.nettychat.common.properties.InitNetty; -import org.apache.commons.lang3.ObjectUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 自动化配置初始化服务 - **/ -@Configuration -@ConditionalOnClass -@EnableConfigurationProperties({InitNetty.class}) -public class ServerAutoConfigure { - - private static final int _BLACKLOG = 1024; - - private static final int CPU =Runtime.getRuntime().availableProcessors(); - - private static final int SEDU_DAY =10; - - private static final int TIMEOUT =120; - - private static final int BUF_SIZE=10*1024*1024; - - - public ServerAutoConfigure(){ - - } - - @Bean - @ConditionalOnMissingBean(name = "sacnScheduled") - public ScanRunnable initRunable(@Autowired InitNetty serverBean){ - long time =(serverBean==null || serverBean.getPeriod()<5)?10:serverBean.getPeriod(); - ScanRunnable sacnScheduled = new SacnScheduled(time); - Thread scanRunnable = new Thread(sacnScheduled); - scanRunnable.setDaemon(true); - scanRunnable.start(); - return sacnScheduled; - } - - - @Bean(initMethod = "open", destroyMethod = "close") - @ConditionalOnMissingBean - public InitServer initServer(InitNetty serverBean){ - if(!ObjectUtils.allNotNull(serverBean.getMqttport(),serverBean.getServerName())){ - throw new NullPointerException("not set port"); - } - if(serverBean.getBacklog()<1){ - serverBean.setBacklog(_BLACKLOG); - } - if(serverBean.getBossThread()<1){ - serverBean.setBossThread(CPU); - } - if(serverBean.getInitalDelay()<0){ - serverBean.setInitalDelay(SEDU_DAY); - } - if(serverBean.getPeriod()<1){ - serverBean.setPeriod(SEDU_DAY); - } - if(serverBean.getHeart()<1){ - serverBean.setHeart(TIMEOUT); - } - if(serverBean.getRevbuf()<1){ - serverBean.setRevbuf(BUF_SIZE); - } - if(serverBean.getWorkerThread()<1){ - serverBean.setWorkerThread(CPU*2); - } - if(serverBean.getProtocol()==null){ - serverBean.setProtocol(ProtocolEnum.MQTT); - } - return new InitServer(serverBean); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/AbstractBootstrapServer.java b/src/main/java/com/myself/nettychat/bootstrap/AbstractBootstrapServer.java deleted file mode 100644 index a647848..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/AbstractBootstrapServer.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.myself.nettychat.bootstrap; - - -import com.myself.nettychat.bootstrap.coder.ByteBufToWebSocketFrameEncoder; -import com.myself.nettychat.bootstrap.coder.WebSocketFrameToByteBufDecoder; -import com.myself.nettychat.common.properties.InitNetty; -import com.myself.nettychat.common.ssl.SecureSocketSslContextFactory; -import com.myself.nettychat.common.utils.SpringBeanUtils; -import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; -import io.netty.handler.codec.mqtt.MqttDecoder; -import io.netty.handler.codec.mqtt.MqttEncoder; -import io.netty.handler.ssl.SslHandler; -import io.netty.handler.timeout.IdleStateHandler; -import org.apache.commons.lang3.ObjectUtils; -import org.jboss.netty.util.internal.SystemPropertyUtil; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import java.security.KeyStore; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 抽象类,负责加载edec handler - **/ -public abstract class AbstractBootstrapServer implements BootstrapServer { - - private String PROTOCOL = "TLS"; - - private SSLContext SERVER_CONTEXT; - - private static final String MQTT_CSV_LIST = "mqtt, mqttv3.1, mqttv3.1.1"; - - - /** - * - * @param channelPipeline channelPipeline - * @param serverBean 服务配置参数 - */ - protected void initHandler(ChannelPipeline channelPipeline, InitNetty serverBean){ - if(serverBean.isSsl()){ - if(!ObjectUtils.allNotNull(serverBean.getJksCertificatePassword(),serverBean.getJksFile(),serverBean.getJksStorePassword())){ - throw new NullPointerException("SSL file and password is null"); - } - initSsl(serverBean); - SSLEngine engine = - SERVER_CONTEXT.createSSLEngine(); - engine.setUseClientMode(false); - channelPipeline.addLast("ssl", new SslHandler(engine)); - } - - intProtocolHandler(channelPipeline,serverBean); - channelPipeline.addLast(new IdleStateHandler(serverBean.getHeart(),0,0)); - channelPipeline.addLast( SpringBeanUtils.getBean(serverBean.getMqttHander())); - - } - - private void intProtocolHandler(ChannelPipeline channelPipeline,InitNetty serverBean){ - switch (serverBean.getProtocol()){ - case MQTT: - channelPipeline.addLast("encoder", MqttEncoder.INSTANCE); - channelPipeline.addLast("decoder", new MqttDecoder()); - break; - case MQTT_WS_MQTT: - channelPipeline.addLast("httpCode", new HttpServerCodec()); - channelPipeline.addLast("aggregator", new HttpObjectAggregator(65536)); - channelPipeline.addLast("webSocketHandler", - new WebSocketServerProtocolHandler("/", MQTT_CSV_LIST)); - channelPipeline.addLast("wsDecoder", new WebSocketFrameToByteBufDecoder()); - channelPipeline.addLast("wsEncoder", new ByteBufToWebSocketFrameEncoder()); - channelPipeline.addLast("decoder", new MqttDecoder()); - channelPipeline.addLast("encoder", MqttEncoder.INSTANCE); - break; - case MQTT_WS_PAHO: - channelPipeline.addLast("httpCode", new HttpServerCodec()); - channelPipeline.addLast("aggregator", new HttpObjectAggregator(65536)); - channelPipeline.addLast("webSocketHandler", - new WebSocketServerProtocolHandler("/mqtt", MQTT_CSV_LIST)); - channelPipeline.addLast("wsDecoder", new WebSocketFrameToByteBufDecoder()); - channelPipeline.addLast("wsEncoder", new ByteBufToWebSocketFrameEncoder()); - channelPipeline.addLast("decoder", new MqttDecoder()); - channelPipeline.addLast("encoder", MqttEncoder.INSTANCE); - break; - } - } - - private void initSsl(InitNetty serverBean){ - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.submit(() -> {}); - String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm"); - if (algorithm == null) { - algorithm = "SunX509"; - } - SSLContext serverContext; - try { - // - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load( SecureSocketSslContextFactory.class.getResourceAsStream(serverBean.getJksFile()), - serverBean.getJksStorePassword().toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); - kmf.init(ks,serverBean.getJksCertificatePassword().toCharArray()); - serverContext = SSLContext.getInstance(PROTOCOL); - serverContext.init(kmf.getKeyManagers(), null, null); - } catch (Exception e) { - throw new Error( - "Failed to initialize the server-side SSLContext", e); - } - SERVER_CONTEXT = serverContext; - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/BaseApi.java b/src/main/java/com/myself/nettychat/bootstrap/BaseApi.java deleted file mode 100644 index edd8720..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/BaseApi.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.myself.nettychat.bootstrap; - -import javax.validation.constraints.NotNull; -import java.util.Arrays; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Predicate; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 逻辑操作封装 - **/ -public interface BaseApi { - - default void doIfElse(T t, Predicate predicate, Consumer consumer){ - if(t!=null){ - if(predicate.test(t)){ - consumer.accept(t); - } - } - } - - - default void doIfElse(T t, Predicate predicate, Consumer consumer, Consumer consumer2){ - if(t!=null){ - if(predicate.test(t)){ - consumer.accept(t); - } - else{ - consumer2.accept(t); - } - } - } - default boolean doIf(T t, Predicate... predicates){ - if(t!=null){ - for(Predicate p:predicates){ - if(!p.test(t)){ - return false; - } - } - return true; - } - return false; - } - - default void doIfAnd(T t, Consumer consumer2, Predicate... predicates){ - boolean flag =true; - if(t!=null){ - for(Predicate p:predicates){ - if(!p.test(t)){ - flag= false; - break; - } - } - } - if(flag){ - consumer2.accept(t); - } - } - - default void doIfAnd1(@NotNull T t, @NotNull Consumer consumer2, @NotNull Predicate... predicates){ - Predicate one = predicates[0]; - int l; - if((l=predicates.length)>1){ - for(int i=1;i topics); - - void loginSuccess(Channel channel, String deviceId, MqttConnectMessage mqttConnectMessage); - - void publishSuccess(Channel channel, MqttPublishMessage mqttPublishMessage); - - void closeSuccess(String deviceId,boolean isDisconnect); - - void sendWillMsg(WillMeaasge willMeaasge); - - String getDeviceId(Channel channel); - - void unsubscribe(String deviceId, List topics1); - - void doPubrel(Channel channel, int mqttMessage); - - void doPubrec(Channel channel, int mqttMessage); - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/NettyBootstrapServer.java b/src/main/java/com/myself/nettychat/bootstrap/NettyBootstrapServer.java deleted file mode 100644 index 816eea7..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/NettyBootstrapServer.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.myself.nettychat.bootstrap; - -import com.myself.nettychat.common.ip.IpUtils; -import com.myself.nettychat.common.properties.InitNetty; -import com.myself.nettychat.common.utils.RemotingUtil; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import io.netty.bootstrap.ServerBootstrap; -import io.netty.buffer.PooledByteBufAllocator; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.epoll.Epoll; -import io.netty.channel.epoll.EpollEventLoopGroup; -import io.netty.channel.epoll.EpollServerSocketChannel; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc mtqq netty启动服务类 - **/ -@Slf4j -@Data -public class NettyBootstrapServer extends AbstractBootstrapServer { - - private InitNetty serverBean; - - public InitNetty getServerBean() { - return serverBean; - } - - public void setServerBean(InitNetty serverBean) { - this.serverBean = serverBean; - } - - private EventLoopGroup bossGroup; - - private EventLoopGroup workGroup; - - ServerBootstrap bootstrap=null ;// 启动辅助类 - - /** - * 服务开启 - */ - public void start() { - initEventPool(); - bootstrap.group(bossGroup, workGroup) - .channel(useEpoll()?EpollServerSocketChannel.class:NioServerSocketChannel.class) - .option(ChannelOption.SO_REUSEADDR, serverBean.isReuseaddr()) - .option(ChannelOption.SO_BACKLOG, serverBean.getBacklog()) - .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - .option(ChannelOption.SO_RCVBUF, serverBean.getRevbuf()) - .childHandler(new ChannelInitializer() { - protected void initChannel(SocketChannel ch) throws Exception { - initHandler(ch.pipeline(),serverBean); - } - }) - .childOption(ChannelOption.TCP_NODELAY, serverBean.isNodelay()) - .childOption(ChannelOption.SO_KEEPALIVE, serverBean.isKeepalive()) - .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); - bootstrap.bind(IpUtils.getHost(),serverBean.getMqttport()).addListener((ChannelFutureListener) channelFuture -> { - if (channelFuture.isSuccess()) - log.info("服务端启动成功【" + IpUtils.getHost() + ":" + serverBean.getMqttport() + "】"); - else - log.info("服务端启动失败【" + IpUtils.getHost() + ":" + serverBean.getMqttport() + "】"); - }); - } - /** - * 初始化EnentPool 参数 - */ - private void initEventPool(){ - bootstrap= new ServerBootstrap(); - if(useEpoll()){ - bossGroup = new EpollEventLoopGroup(serverBean.getBossThread(), new ThreadFactory() { - private AtomicInteger index = new AtomicInteger(0); - - public Thread newThread(Runnable r) { - return new Thread(r, "LINUX_BOSS_" + index.incrementAndGet()); - } - }); - workGroup = new EpollEventLoopGroup(serverBean.getWorkerThread(), new ThreadFactory() { - private AtomicInteger index = new AtomicInteger(0); - - public Thread newThread(Runnable r) { - return new Thread(r, "LINUX_WORK_" + index.incrementAndGet()); - } - }); - - } - else { - bossGroup = new NioEventLoopGroup(serverBean.getBossThread(), new ThreadFactory() { - private AtomicInteger index = new AtomicInteger(0); - - public Thread newThread(Runnable r) { - return new Thread(r, "BOSS_" + index.incrementAndGet()); - } - }); - workGroup = new NioEventLoopGroup(serverBean.getWorkerThread(), new ThreadFactory() { - private AtomicInteger index = new AtomicInteger(0); - - public Thread newThread(Runnable r) { - return new Thread(r, "WORK_" + index.incrementAndGet()); - } - }); - } - } - - /** - * 关闭资源 - */ - public void shutdown() { - if(workGroup!=null && bossGroup!=null ){ - try { - bossGroup.shutdownGracefully().sync();// 优雅关闭 - workGroup.shutdownGracefully().sync(); - } catch (InterruptedException e) { - log.info("服务端关闭资源失败【" + IpUtils.getHost() + ":" + serverBean.getMqttport() + "】"); - } - } - } - - private boolean useEpoll() { - return RemotingUtil.isLinuxPlatform() - && Epoll.isAvailable(); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/bean/MqttChannel.java b/src/main/java/com/myself/nettychat/bootstrap/bean/MqttChannel.java deleted file mode 100644 index 9c830ce..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/bean/MqttChannel.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.myself.nettychat.bootstrap.bean; - -import io.netty.channel.Channel; -import io.netty.util.AttributeKey; -import lombok.Builder; -import lombok.Data; - -import com.myself.nettychat.common.enums.SubStatus; -import com.myself.nettychat.common.enums.SessionStatus; - -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc channel 封装类 - **/ -@Builder -@Data -public class MqttChannel { - - private transient volatile Channel channel; - - - private String deviceId; - - - private boolean isWill; - - - private volatile SubStatus subStatus; // 是否订阅过主题 - - - private Set topic ; - - - - private volatile SessionStatus sessionStatus; // 在线 - 离线 - - - - private volatile boolean cleanSession; // 当为 true 时 channel close 时 从缓存中删除 此channel - - - - - private ConcurrentHashMap message ; // messageId - message(qos1) // 待确认消息 - - - private Set receive; - - public void addRecevice(int messageId){ - receive.add(messageId); - } - - public boolean checkRecevice(int messageId){ - return receive.contains(messageId); - } - - public boolean removeRecevice(int messageId){ - return receive.remove(messageId); - } - - - public void addSendMqttMessage(int messageId,SendMqttMessage msg){ - message.put(messageId,msg); - } - - - public SendMqttMessage getSendMqttMessage(int messageId){ - return message.get(messageId); - } - - - public void removeSendMqttMessage(int messageId){ - message.remove(messageId); - } - - - /** - * 判断当前channel 是否登录过 - * @return - */ - public boolean isLogin(){ - return Optional.ofNullable(this.channel).map(channel1 -> { - AttributeKey _login = AttributeKey.valueOf("login"); - return channel1.isActive() && channel1.hasAttr(_login); - }).orElse(false); - } - - /** - * 非正常关闭 - */ - public void close(){ - Optional.ofNullable(this.channel).ifPresent(channel1 -> channel1.close()); - } - - /** - * 通道是否活跃 - * @return - */ - public boolean isActive(){ - return channel!=null&&this.channel.isActive(); - } - - - - public boolean addTopic(Set topics){ - return topic.addAll(topics); - } - - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/bean/RetainMessage.java b/src/main/java/com/myself/nettychat/bootstrap/bean/RetainMessage.java deleted file mode 100644 index 814696a..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/bean/RetainMessage.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.myself.nettychat.bootstrap.bean; - -import io.netty.handler.codec.mqtt.MqttQoS; -import lombok.Builder; -import lombok.Data; - -@Builder -@Data -public class RetainMessage { - - private byte[] byteBuf; - - private MqttQoS qoS; - public String getString(){ - return new String(byteBuf); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/bean/SendMqttMessage.java b/src/main/java/com/myself/nettychat/bootstrap/bean/SendMqttMessage.java deleted file mode 100644 index ac5faef..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/bean/SendMqttMessage.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.myself.nettychat.bootstrap.bean; - - -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.MqttQoS; -import lombok.Builder; -import lombok.Data; - -import com.myself.nettychat.common.enums.ConfirmStatus; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc mqtts 消息 - **/ -@Builder -@Data -public class SendMqttMessage { - - - private int messageId; - - private Channel channel; - - private volatile ConfirmStatus confirmStatus; - - private long time; - - private byte[] byteBuf; - - private boolean isRetain; - - private MqttQoS qos; - - private String topic; - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/bean/SessionMessage.java b/src/main/java/com/myself/nettychat/bootstrap/bean/SessionMessage.java deleted file mode 100644 index 2613cd6..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/bean/SessionMessage.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.myself.nettychat.bootstrap.bean; - - -import io.netty.handler.codec.mqtt.MqttQoS; -import lombok.Builder; -import lombok.Data; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc Session会话数据保存 - **/ -@Builder -@Data -public class SessionMessage { - - private byte[] byteBuf; - - private MqttQoS qoS; - - private String topic; - - - public String getString(){ - return new String(byteBuf); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/bean/WillMeaasge.java b/src/main/java/com/myself/nettychat/bootstrap/bean/WillMeaasge.java deleted file mode 100644 index 4022d28..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/bean/WillMeaasge.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.myself.nettychat.bootstrap.bean; - -import lombok.Builder; -import lombok.Data; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 遗嘱消息 - **/ -@Builder -@Data -public class WillMeaasge { - - private String willTopic; - - private String willMessage; - - private boolean isRetain; - - private int qos; - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/AbstractChannelService.java b/src/main/java/com/myself/nettychat/bootstrap/channel/AbstractChannelService.java deleted file mode 100644 index c0e51f2..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/AbstractChannelService.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.BaseApi; -import com.myself.nettychat.bootstrap.ChannelService; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.myself.nettychat.bootstrap.bean.MqttChannel; -import com.myself.nettychat.bootstrap.bean.RetainMessage; -import com.myself.nettychat.bootstrap.channel.cache.CacheMap; -import com.myself.nettychat.bootstrap.scan.ScanRunnable; -import io.netty.channel.Channel; -import io.netty.util.AttributeKey; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; - -import java.util.Collection; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 抽象类 - **/ -@Slf4j -public abstract class AbstractChannelService extends PublishApiSevice implements ChannelService , BaseApi { - - protected AttributeKey _login = AttributeKey.valueOf("login"); - - protected AttributeKey _deviceId = AttributeKey.valueOf("deviceId"); - - protected static char SPLITOR = '/'; - - protected ExecutorService executorService =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2); - - - protected static CacheMap cacheMap= new CacheMap<>(); - - - protected static ConcurrentHashMap mqttChannels = new ConcurrentHashMap<>(); // deviceId - mqChannel 登录 - - - protected static ConcurrentHashMap> retain = new ConcurrentHashMap<>(); // topic - 保留消息 - - - - protected static Cache> mqttChannelCache = CacheBuilder.newBuilder().maximumSize(100).build(); - - public AbstractChannelService(ScanRunnable scanRunnable) { - super(scanRunnable); - } - - - protected Collection getChannels(String topic,TopicFilter topicFilter){ - try { - return mqttChannelCache.get(topic, () -> topicFilter.filter(topic)); - } catch (Exception e) { - log.info(String.format("guava cache key topic【%s】 channel value== null ",topic)); - } - return null; - } - - - @FunctionalInterface - interface TopicFilter{ - Collection filter(String topic); - } - - protected boolean deleteChannel(String topic,MqttChannel mqttChannel){ - return Optional.ofNullable(topic).map(s -> { - mqttChannelCache.invalidate(s); - return cacheMap.delete(getTopic(s),mqttChannel); - }).orElse(false); - } - - protected boolean addChannel(String topic,MqttChannel mqttChannel) - { - return Optional.ofNullable(topic).map(s -> { - mqttChannelCache.invalidate(s); - return cacheMap.putData(getTopic(s),mqttChannel); - }).orElse(false); - } - - /** - * 获取channel - */ - public MqttChannel getMqttChannel(String deviceId){ - return Optional.ofNullable(deviceId).map(s -> mqttChannels.get(s)) - .orElse(null); - - } - - /** - * 获取channelId - */ - public String getDeviceId(Channel channel){ - return Optional.ofNullable(channel).map( channel1->channel1.attr(_deviceId).get()) - .orElse(null); - } - - - - protected String[] getTopic(String topic) { - return Optional.ofNullable(topic).map(s -> - StringUtils.split(topic,SPLITOR) - ).orElse(null); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/ClientSessionService.java b/src/main/java/com/myself/nettychat/bootstrap/channel/ClientSessionService.java deleted file mode 100644 index 9a23c8b..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/ClientSessionService.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.bean.SessionMessage; -import org.springframework.stereotype.Service; - -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 会话保留处理 - **/ -@Service -public class ClientSessionService { - - private static ConcurrentHashMap> queueSession = new ConcurrentHashMap<>(); // 连接关闭后 保留此session 数据 deviceId - - - public void saveSessionMsg(String deviceId, SessionMessage sessionMessage) { - ConcurrentLinkedQueue sessionMessages = queueSession.getOrDefault(deviceId, new ConcurrentLinkedQueue<>()); - boolean flag; - do{ - flag = sessionMessages.add(sessionMessage); - } - while (!flag); - queueSession.put(deviceId,sessionMessages); - } - - public ConcurrentLinkedQueue getByteBuf(String deviceId){ - return Optional.ofNullable(deviceId).map(s -> queueSession.get(s)) - .orElse(null); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/MqttChannelService.java b/src/main/java/com/myself/nettychat/bootstrap/channel/MqttChannelService.java deleted file mode 100644 index fa5ec21..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/MqttChannelService.java +++ /dev/null @@ -1,440 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.bean.*; -import com.myself.nettychat.bootstrap.scan.ScanRunnable; -import com.myself.nettychat.common.enums.ConfirmStatus; -import com.myself.nettychat.common.enums.SessionStatus; -import com.myself.nettychat.common.enums.SubStatus; -import com.myself.nettychat.common.exception.ConnectionException; -import com.myself.nettychat.common.utils.ByteBufUtil; -import io.netty.buffer.ByteBuf; -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArraySet; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc Channel事件处理service - **/ -@Slf4j -@Component -public class MqttChannelService extends AbstractChannelService { - - @Autowired - private ClientSessionService clientSessionService; - - @Autowired - private WillService willService; - - private final ScanRunnable scanRunnable; - - public MqttChannelService(ScanRunnable scanRunnable) { - super(scanRunnable); - this.scanRunnable = scanRunnable; - } - - - /** - * 取消订阅 - */ - @Override - public void unsubscribe(String deviceId, List topics1) { - Optional.ofNullable(mqttChannels.get(deviceId)).ifPresent(mqttChannel -> { - topics1.forEach(topic -> { - deleteChannel(topic,mqttChannel); - }); - }); - } - - /** - * 登录成功后 回复 - */ - private void replyLogin(Channel channel, MqttConnectMessage mqttConnectMessage) { - MqttFixedHeader mqttFixedHeader1 = mqttConnectMessage.fixedHeader(); - MqttConnectVariableHeader mqttConnectVariableHeader = mqttConnectMessage.variableHeader(); - final MqttConnectPayload payload = mqttConnectMessage.payload(); - String deviceId = getDeviceId(channel); - MqttChannel build = MqttChannel.builder().channel(channel).cleanSession(mqttConnectVariableHeader.isCleanSession()) - .deviceId(payload.clientIdentifier()) - .sessionStatus(SessionStatus.OPEN) - .isWill(mqttConnectVariableHeader.isWillFlag()) - .subStatus(SubStatus.NO) - .topic(new CopyOnWriteArraySet<>()) - .message(new ConcurrentHashMap<>()) - .receive(new CopyOnWriteArraySet<>()) - .build(); - if (connectSuccess(deviceId, build)) { // 初始化存储mqttchannel - if (mqttConnectVariableHeader.isWillFlag()) { // 遗嘱消息标志 - boolean b = doIf(mqttConnectVariableHeader, mqttConnectVariableHeader1 -> (payload.willMessage() != null) - , mqttConnectVariableHeader1 -> (payload.willTopic() != null)); - if (!b) { - throw new ConnectionException("will message and will topic is not null"); - } - // 处理遗嘱消息 - final WillMeaasge buildWill = WillMeaasge.builder(). - qos(mqttConnectVariableHeader.willQos()) - .willMessage(deviceId) - .willTopic(payload.willTopic()) - .isRetain(mqttConnectVariableHeader.isWillRetain()) - .build(); - willService.save(payload.clientIdentifier(), buildWill); - } else { - willService.del(payload.clientIdentifier()); - boolean b = doIf(mqttConnectVariableHeader, mqttConnectVariableHeader1 -> (!mqttConnectVariableHeader1.isWillRetain()), - mqttConnectVariableHeader1 -> (mqttConnectVariableHeader1.willQos() == 0)); - if (!b) { - throw new ConnectionException("will retain should be null and will QOS equal 0"); - } - } - doIfElse(mqttConnectVariableHeader, mqttConnectVariableHeader1 -> (mqttConnectVariableHeader1.isCleanSession()), mqttConnectVariableHeader1 -> { - MqttConnectReturnCode connectReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED; - MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(connectReturnCode, false); - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader( - MqttMessageType.CONNACK, mqttFixedHeader1.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeader1.isRetain(), 0x02); - MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader); - channel.writeAndFlush(connAck);// 清理会话 - }, mqttConnectVariableHeader1 -> { - MqttConnectReturnCode connectReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED; - MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(connectReturnCode, true); - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader( - MqttMessageType.CONNACK, mqttFixedHeader1.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeader1.isRetain(), 0x02); - MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader); - channel.writeAndFlush(connAck);// 非清理会话 - - }); //发送 session 数据 - ConcurrentLinkedQueue sessionMessages = clientSessionService.getByteBuf(payload.clientIdentifier()); - doIfElse(sessionMessages, messages -> messages != null && !messages.isEmpty(), byteBufs -> { - SessionMessage sessionMessage; - while ((sessionMessage = byteBufs.poll()) != null) { - switch (sessionMessage.getQoS()) { - case EXACTLY_ONCE: - sendQosConfirmMsg(MqttQoS.EXACTLY_ONCE,getMqttChannel(deviceId), sessionMessage.getTopic(), sessionMessage.getByteBuf()); - break; - case AT_MOST_ONCE: - sendQos0Msg(channel, sessionMessage.getTopic(), sessionMessage.getByteBuf()); - break; - case AT_LEAST_ONCE: - sendQosConfirmMsg(MqttQoS.AT_LEAST_ONCE,getMqttChannel(deviceId), sessionMessage.getTopic(), sessionMessage.getByteBuf()); - break; - } - } - - }); - } - } - - - - /** - * qos2 第二步 - */ - @Override - public void doPubrel(Channel channel, int messageId) { - MqttChannel mqttChannel = getMqttChannel(getDeviceId(channel)); - doIfElse(mqttChannel,mqttChannel1 ->mqttChannel1.isLogin(),mqttChannel1 -> { - mqttChannel1.removeRecevice(messageId); - sendToPubComp(channel,messageId); - }); - } - - - - /** - * qos2 第三步 - */ - @Override - public void doPubrec(Channel channel, int mqttMessage) { - sendPubRel(channel,false,mqttMessage); - } - - /** - * 连接成功后 - * @param deviceId - * @param build - */ - @Override - public boolean connectSuccess(String deviceId, MqttChannel build) { - return Optional.ofNullable(mqttChannels.get(deviceId)) - .map(mqttChannel -> { - switch (mqttChannel.getSessionStatus()){ - case OPEN: - return false; - case CLOSE: - switch (mqttChannel.getSubStatus()){ - case YES: // 清除订阅 topic - deleteSubTopic(mqttChannel).stream() - .forEach(s -> cacheMap.putData(getTopic(s),build)); - break; - } - } - mqttChannels.put(deviceId,build); - return true; - }).orElseGet(() -> { - mqttChannels.put(deviceId,build); - return true; - }); - } - - - /** - * 订阅成功后 (发送保留消息) - */ - public void suscribeSuccess(String deviceId, Set topics){ - doIfElse(topics,topics1->!CollectionUtils.isEmpty(topics1),strings -> { - MqttChannel mqttChannel = mqttChannels.get(deviceId); - mqttChannel.setSubStatus(SubStatus.YES); // 设置订阅主题标识 - mqttChannel.addTopic(strings); - executorService.execute(() -> { - Optional.ofNullable(mqttChannel).ifPresent(mqttChannel1 -> { - if(mqttChannel1.isLogin()){ - strings.parallelStream().forEach(topic -> { - addChannel(topic,mqttChannel); - sendRetain(topic,mqttChannel); // 发送保留消息 - }); - } - }); - }); - }); - } - - - /** - *成功登陆 (发送会话消息) - * @param channel - * @param deviceId - * @param mqttConnectMessage - */ - @Override - public void loginSuccess(Channel channel, String deviceId, MqttConnectMessage mqttConnectMessage) { - channel.attr(_login).set(true); - channel.attr(_deviceId).set(deviceId); - replyLogin(channel, mqttConnectMessage); - } - - - /** - * 发布消息成功 () - * @param channel - * @param mqttPublishMessage - */ - @Override - public void publishSuccess(Channel channel, MqttPublishMessage mqttPublishMessage) { - MqttFixedHeader mqttFixedHeader = mqttPublishMessage.fixedHeader(); - MqttPublishVariableHeader mqttPublishVariableHeader = mqttPublishMessage.variableHeader(); - MqttChannel mqttChannel = getMqttChannel(getDeviceId(channel)); - ByteBuf payload = mqttPublishMessage.payload(); - byte[] bytes = ByteBufUtil.copyByteBuf(payload); // - int messageId = mqttPublishVariableHeader.messageId(); - executorService.execute(() -> { - if (channel.hasAttr(_login) && mqttChannel != null) { - boolean isRetain; - switch (mqttFixedHeader.qosLevel()) { - case AT_MOST_ONCE: // 至多一次 - break; - case AT_LEAST_ONCE: - sendPubBack(channel, messageId); - break; - case EXACTLY_ONCE: - sendPubRec(mqttChannel, messageId); - break; - } - if ((isRetain=mqttFixedHeader.isRetain()) && mqttFixedHeader.qosLevel() != MqttQoS.AT_MOST_ONCE) { //是保留消息 qos >0 - saveRetain(mqttPublishVariableHeader.topicName(), - RetainMessage.builder() - .byteBuf(bytes) - .qoS(mqttFixedHeader.qosLevel()) - .build(), false); - } else if (mqttFixedHeader.isRetain() && mqttFixedHeader.qosLevel() == MqttQoS.AT_MOST_ONCE) { // 是保留消息 qos=0 清除之前保留消息 保留现在 - saveRetain(mqttPublishVariableHeader.topicName(), - RetainMessage.builder() - .byteBuf(bytes) - .qoS(mqttFixedHeader.qosLevel()) - .build(), true); - } - if (!mqttChannel.checkRecevice(messageId)) { - push(mqttPublishVariableHeader.topicName(), mqttFixedHeader.qosLevel(), bytes,isRetain); - mqttChannel.addRecevice(messageId); - } - } - }); - - } - /** - * 推送消息给订阅者 - */ - private void push(String topic, MqttQoS qos, byte[] bytes, boolean isRetain){ - Collection subChannels = getChannels(topic, topic1 -> cacheMap.getData(getTopic(topic1))); - if(!CollectionUtils.isEmpty(subChannels)){ - subChannels.parallelStream().forEach(subChannel -> { - switch (subChannel.getSessionStatus()){ - case OPEN: // 在线 - if(subChannel.isActive()){ // 防止channel失效 但是离线状态没更改 - switch (qos){ - case AT_LEAST_ONCE: - sendQosConfirmMsg(MqttQoS.AT_LEAST_ONCE,subChannel,topic,bytes); - break; - case AT_MOST_ONCE: - sendQos0Msg(subChannel.getChannel(),topic,bytes); - break; - case EXACTLY_ONCE: - sendQosConfirmMsg(MqttQoS.EXACTLY_ONCE,subChannel,topic,bytes); - break; - } - } - else{ - if(!subChannel.isCleanSession() & !isRetain){ - clientSessionService.saveSessionMsg(subChannel.getDeviceId(), - SessionMessage.builder().byteBuf(bytes).qoS(qos).topic(topic).build() ); - break; - } - } - break; - case CLOSE: // 连接 设置了 clean session =false - clientSessionService.saveSessionMsg(subChannel.getDeviceId(), - SessionMessage.builder().byteBuf(bytes).qoS(qos).topic(topic).build() ); - break; - } - }); - } - } - - /** - * 关闭channel 操作 - * @param deviceId - */ - @Override - public void closeSuccess(String deviceId,boolean isDisconnect) { - if(StringUtils.isNotBlank(deviceId)){ - executorService.execute(() -> { - MqttChannel mqttChannel = mqttChannels.get(deviceId); - Optional.ofNullable(mqttChannel).ifPresent(mqttChannel1 -> { - mqttChannel1.setSessionStatus(SessionStatus.CLOSE); // 设置关闭 - mqttChannel1.close(); // 关闭channel - mqttChannel1.setChannel(null); - if(!mqttChannel1.isCleanSession()){ // 保持会话 - // 处理 qos1 未确认数据 - ConcurrentHashMap message = mqttChannel1.getMessage(); - Optional.ofNullable(message).ifPresent(integerConfirmMessageConcurrentHashMap -> { - integerConfirmMessageConcurrentHashMap.forEach((integer, confirmMessage) -> doIfElse(confirmMessage, sendMqttMessage ->sendMqttMessage.getConfirmStatus()== ConfirmStatus.PUB, sendMqttMessage ->{ - clientSessionService.saveSessionMsg(mqttChannel.getDeviceId(), SessionMessage.builder() - .byteBuf(sendMqttMessage.getByteBuf()) - .qoS(sendMqttMessage.getQos()) - .topic(sendMqttMessage.getTopic()) - .build()); // 把待确认数据转入session中 - } - )); - - }); - } - else{ // 删除sub topic-消息 - mqttChannels.remove(deviceId); // 移除channelId 不保持会话 直接删除 保持会话 旧的在重新connect时替换 - switch (mqttChannel1.getSubStatus()){ - case YES: - deleteSubTopic(mqttChannel1); - break; - } - } - if(mqttChannel1.isWill()){ // 发送遗言 - if(!isDisconnect){ // 不是disconnection操作 - willService.doSend(deviceId); - } - } - }); - }); - } - } - - /** - * 清除channel 订阅主题 - * @param mqttChannel - */ - public Set deleteSubTopic(MqttChannel mqttChannel){ - Set topics = mqttChannel.getTopic(); - topics.parallelStream().forEach(topic -> cacheMap.delete(getTopic(topic),mqttChannel)); - return topics; - } - - /** - * 发送 遗嘱消息(有的channel 已经关闭 但是保持了 session 此时加入session 数据中 ) - * @param willMeaasge 遗嘱消息 - */ - public void sendWillMsg(WillMeaasge willMeaasge){ - Collection mqttChannels = getChannels(willMeaasge.getWillTopic(), topic -> cacheMap.getData(getTopic(topic))); - if(!CollectionUtils.isEmpty(mqttChannels)){ - mqttChannels.forEach(mqttChannel -> { - switch (mqttChannel.getSessionStatus()){ - case CLOSE: - clientSessionService.saveSessionMsg(mqttChannel.getDeviceId(), - SessionMessage.builder() - .topic(willMeaasge.getWillTopic()) - .qoS(MqttQoS.valueOf(willMeaasge.getQos())) - .byteBuf(willMeaasge.getWillMessage().getBytes()).build()); - break; - case OPEN: - writeWillMsg(mqttChannel,willMeaasge); - break; - } - }); - } - } - - /** - * 保存保留消息 - * @param topic 主题 - * @param retainMessage 信息 - */ - private void saveRetain(String topic, RetainMessage retainMessage, boolean isClean){ - ConcurrentLinkedQueue retainMessages = retain.getOrDefault(topic, new ConcurrentLinkedQueue<>()); - if(!retainMessages.isEmpty() && isClean){ - retainMessages.clear(); - } - boolean flag; - do{ - flag = retainMessages.add(retainMessage); - } - while (!flag); - retain.put(topic, retainMessages); - } - - /** - * 发送保留消息 - */ - public void sendRetain(String topic,MqttChannel mqttChannel){ - retain.forEach((_topic, retainMessages) -> { - if(StringUtils.startsWith(_topic,topic)){ - Optional.ofNullable(retainMessages).ifPresent(pubMessages1 -> { - retainMessages.parallelStream().forEach(retainMessage -> { - log.info("【发送保留消息】"+mqttChannel.getChannel().remoteAddress()+":"+retainMessage.getString()+"【成功】"); - switch (retainMessage.getQoS()){ - case AT_MOST_ONCE: - sendQos0Msg(mqttChannel.getChannel(),_topic,retainMessage.getByteBuf()); - break; - case AT_LEAST_ONCE: - sendQosConfirmMsg(MqttQoS.AT_LEAST_ONCE,mqttChannel,_topic,retainMessage.getByteBuf()); - break; - case EXACTLY_ONCE: - sendQosConfirmMsg(MqttQoS.EXACTLY_ONCE,mqttChannel,_topic,retainMessage.getByteBuf()); - break; - } - }); - }); - } - }); - - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/MqttHandlerService.java b/src/main/java/com/myself/nettychat/bootstrap/channel/MqttHandlerService.java deleted file mode 100644 index abc4d56..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/MqttHandlerService.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.BaseApi; -import com.myself.nettychat.bootstrap.BaseAuthService; -import com.myself.nettychat.bootstrap.ChannelService; -import com.myself.nettychat.bootstrap.bean.SendMqttMessage; -import com.myself.nettychat.common.enums.ConfirmStatus; -import com.myself.nettychat.common.mqtts.ServerMqttHandlerService; -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import io.netty.handler.timeout.IdleStateEvent; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@Slf4j -@Component -public class MqttHandlerService extends ServerMqttHandlerService implements BaseApi { - - @Autowired - ChannelService mqttChannelService; - - private final BaseAuthService baseAuthService; - - public MqttHandlerService(BaseAuthService baseAuthService) { - this.baseAuthService = baseAuthService; - } - - /** - * 登录 - * - */ - @Override - public boolean login(Channel channel, MqttConnectMessage mqttConnectMessage) { -// 校验规则 自定义校验规则 - MqttConnectPayload payload = mqttConnectMessage.payload(); - String deviceId = payload.clientIdentifier(); - if (StringUtils.isBlank(deviceId)) { - MqttConnectReturnCode connectReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED; - connectBack(channel,connectReturnCode); - return false; - } - - if(mqttConnectMessage.variableHeader().hasPassword() && mqttConnectMessage.variableHeader().hasUserName() - && !baseAuthService.authorized(payload.userName(),payload.password())){ - MqttConnectReturnCode connectReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD; - connectBack(channel,connectReturnCode); - return false; - } - return Optional.ofNullable(mqttChannelService.getMqttChannel(deviceId)) - .map(mqttChannel -> { - switch (mqttChannel.getSessionStatus()){ - case OPEN: - return false; - } - mqttChannelService.loginSuccess(channel, deviceId, mqttConnectMessage); - return true; - }).orElseGet(() -> { - mqttChannelService.loginSuccess(channel, deviceId, mqttConnectMessage); - return true; - }); - - } - - private void connectBack(Channel channel, MqttConnectReturnCode connectReturnCode){ - MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(connectReturnCode, true); - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader( - MqttMessageType.CONNACK,false, MqttQoS.AT_MOST_ONCE, false, 0x02); - MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader); - channel.writeAndFlush(connAck); - } - - - /** - * 发布 - */ - @Override - public void publish(Channel channel, MqttPublishMessage mqttPublishMessage) { - mqttChannelService.publishSuccess(channel, mqttPublishMessage); - } - - /** - * 订阅 - */ - @Override - public void subscribe(Channel channel, MqttSubscribeMessage mqttSubscribeMessage) { - Set topics = mqttSubscribeMessage.payload().topicSubscriptions().stream().map(mqttTopicSubscription -> - mqttTopicSubscription.topicName() - ).collect(Collectors.toSet()); - mqttChannelService.suscribeSuccess(mqttChannelService.getDeviceId(channel), topics); - subBack(channel, mqttSubscribeMessage, topics.size()); - } - - private void subBack(Channel channel, MqttSubscribeMessage mqttSubscribeMessage, int num) { - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0); - MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(mqttSubscribeMessage.variableHeader().messageId()); - List grantedQoSLevels = new ArrayList<>(num); - for (int i = 0; i < num; i++) { - grantedQoSLevels.add(mqttSubscribeMessage.payload().topicSubscriptions().get(i).qualityOfService().value()); - } - MqttSubAckPayload payload = new MqttSubAckPayload(grantedQoSLevels); - MqttSubAckMessage mqttSubAckMessage = new MqttSubAckMessage(mqttFixedHeader, variableHeader, payload); - channel.writeAndFlush(mqttSubAckMessage); - } - - - /** - * 关闭通道 - */ - @Override - public void close(Channel channel) { - mqttChannelService.closeSuccess(mqttChannelService.getDeviceId(channel), false); - channel.close(); - } - - /** - * 回复pong消息 - */ - @Override - public void pong(Channel channel) { - if (channel.isOpen() && channel.isActive() && channel.isWritable()) { - log.info("收到来自:【" + channel.remoteAddress().toString() + "】心跳"); - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0); - channel.writeAndFlush(new MqttMessage(fixedHeader)); - } - } - - /** - * 取消订阅 - */ - @Override - public void unsubscribe(Channel channel, MqttUnsubscribeMessage mqttMessage) { - List topics1 = mqttMessage.payload().topics(); - mqttChannelService.unsubscribe(mqttChannelService.getDeviceId(channel), topics1); - unSubBack(channel, mqttMessage.variableHeader().messageId()); - } - - /** - * 回复取消订阅 - */ - private void unSubBack(Channel channel, int messageId) { - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0x02); - MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(messageId); - MqttUnsubAckMessage mqttUnsubAckMessage = new MqttUnsubAckMessage(mqttFixedHeader, variableHeader); - channel.writeAndFlush(mqttUnsubAckMessage); - } - - - /** - * 消息回复确认(qos1 级别 保证收到消息 但是可能会重复) - */ - @Override - public void puback(Channel channel, MqttMessage mqttMessage) { - MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader(); - int messageId = messageIdVariableHeader.messageId(); - mqttChannelService.getMqttChannel(mqttChannelService.getDeviceId(channel)).getSendMqttMessage(messageId).setConfirmStatus(ConfirmStatus.COMPLETE); // 复制为空 - } - - - /** - * disconnect 主动断线 - */ - @Override - public void disconnect(Channel channel) { - mqttChannelService.closeSuccess(mqttChannelService.getDeviceId(channel), true); - } - - - /** - * qos2 发布收到 - */ - @Override - public void pubrec(Channel channel, MqttMessage mqttMessage ) { - MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader(); - int messageId = messageIdVariableHeader.messageId(); - mqttChannelService.getMqttChannel(mqttChannelService.getDeviceId(channel)).getSendMqttMessage(messageId).setConfirmStatus(ConfirmStatus.PUBREL); // 复制为空 - mqttChannelService.doPubrec(channel, messageId); - } - - /** - * qos2 发布释放 - */ - @Override - public void pubrel(Channel channel, MqttMessage mqttMessage ) { - MqttMessageIdVariableHeader mqttMessageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader(); - int messageId = mqttMessageIdVariableHeader.messageId(); - mqttChannelService.getMqttChannel(mqttChannelService.getDeviceId(channel)).getSendMqttMessage(messageId).setConfirmStatus(ConfirmStatus.COMPLETE); // 复制为空 - mqttChannelService.doPubrel(channel, messageId); - - } - - /** - * qos2 发布完成 - */ - @Override - public void pubcomp(Channel channel, MqttMessage mqttMessage ) { - MqttMessageIdVariableHeader mqttMessageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader(); - int messageId = mqttMessageIdVariableHeader.messageId(); - SendMqttMessage sendMqttMessage = mqttChannelService.getMqttChannel(mqttChannelService.getDeviceId(channel)).getSendMqttMessage(messageId); - sendMqttMessage.setConfirmStatus(ConfirmStatus.COMPLETE); // 复制为空 - } - - @Override - public void doTimeOut(Channel channel, IdleStateEvent evt) { - log.info("【PingPongService:doTimeOut 心跳超时】" + channel.remoteAddress() + "【channel 关闭】"); - switch (evt.state()) { - case READER_IDLE: - close(channel); - case WRITER_IDLE: - close(channel); - case ALL_IDLE: - close(channel); - } - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/PublishApiSevice.java b/src/main/java/com/myself/nettychat/bootstrap/channel/PublishApiSevice.java deleted file mode 100644 index 4af733f..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/PublishApiSevice.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.bean.MqttChannel; -import com.myself.nettychat.bootstrap.bean.SendMqttMessage; -import com.myself.nettychat.bootstrap.bean.WillMeaasge; -import com.myself.nettychat.bootstrap.scan.ScanRunnable; -import com.myself.nettychat.common.utils.MessageId; -import com.myself.nettychat.common.enums.ConfirmStatus; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import lombok.extern.slf4j.Slf4j; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 发送消息以及确认 - **/ -@Slf4j -public class PublishApiSevice { - - private final ScanRunnable scanRunnable; - - public PublishApiSevice(ScanRunnable scanRunnable) { - this.scanRunnable = scanRunnable; - } - - - /** - * 写入遗嘱消息 - */ - protected void writeWillMsg(MqttChannel mqttChannel, WillMeaasge willMeaasge) { -// dup保证消息可靠传输,默认为0,只占用一个字节,表示第一次发送。不能用于检测消息重复发送等 - switch (willMeaasge.getQos()){ - case 0: // qos0 - sendQos0Msg(mqttChannel.getChannel(),willMeaasge.getWillTopic(),willMeaasge.getWillMessage().getBytes()); - break; - case 1: // qos1 - sendQosConfirmMsg(MqttQoS.AT_LEAST_ONCE,mqttChannel,willMeaasge.getWillTopic(),willMeaasge.getWillMessage().getBytes()); - break; - case 2: // qos2 - sendQosConfirmMsg(MqttQoS.EXACTLY_ONCE,mqttChannel,willMeaasge.getWillTopic(),willMeaasge.getWillMessage().getBytes()); - break; - } - - - } - - protected void sendQosConfirmMsg(MqttQoS qos, MqttChannel mqttChannel, String topic, byte[] bytes) { - if(mqttChannel.isLogin()){ - int messageId = MessageId.messageId(); - switch (qos){ - case AT_LEAST_ONCE: - mqttChannel.addSendMqttMessage(messageId,sendQos1Msg(mqttChannel.getChannel(),topic,false,bytes,messageId)); - break; - case EXACTLY_ONCE: - mqttChannel.addSendMqttMessage(messageId,sendQos2Msg(mqttChannel.getChannel(),topic,false,bytes,messageId)); - break; - } - } - - } - - - /** - * 发送 qos1 类的消息 - */ - private SendMqttMessage sendQos1Msg(Channel channel, String topic, boolean isDup, byte[] byteBuf, int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,isDup, MqttQoS.AT_LEAST_ONCE,false,0); - MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic,messageId ); - MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader,mqttPublishVariableHeader, Unpooled.wrappedBuffer(byteBuf)); - channel.writeAndFlush(mqttPublishMessage); - return addQueue(channel,messageId,topic,byteBuf,MqttQoS.AT_LEAST_ONCE, ConfirmStatus.PUB); - } - - - - /** - * 发送 qos0 类的消息 byte - */ - protected void sendQos0Msg(Channel channel, String topic, byte[] byteBuf){ - if(channel!=null){ - sendQos0Msg(channel,topic,byteBuf,0); - } - } - private void sendQos0Msg(Channel channel, String topic, byte[] byteBuf,int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,false, MqttQoS.AT_MOST_ONCE,false,0); - MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic,messageId ); - MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader,mqttPublishVariableHeader,Unpooled.wrappedBuffer(byteBuf)); - channel.writeAndFlush(mqttPublishMessage); - } - - - - - private SendMqttMessage sendQos2Msg(Channel channel, String topic,boolean isDup, byte[] byteBuf, int messageId) { - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,isDup, MqttQoS.EXACTLY_ONCE,false,0); - MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic,messageId ); - MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader,mqttPublishVariableHeader, Unpooled.wrappedBuffer(byteBuf)); - channel.writeAndFlush(mqttPublishMessage); - return addQueue(channel,messageId,topic,byteBuf,MqttQoS.EXACTLY_ONCE,ConfirmStatus.PUB); - } - - - /** - * 发送qos1 publish 确认消息 - */ - protected void sendPubBack(Channel channel,int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBACK,false, MqttQoS.AT_MOST_ONCE,false,0x02); - MqttMessageIdVariableHeader from = MqttMessageIdVariableHeader.from(messageId); - MqttPubAckMessage mqttPubAckMessage = new MqttPubAckMessage(mqttFixedHeader,from); - channel.writeAndFlush(mqttPubAckMessage); - } - - - /** - * 发送qos2 publish 确认消息 第一步 - */ - protected void sendPubRec( MqttChannel mqttChannel,int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC,false, MqttQoS.AT_LEAST_ONCE,false,0x02); - MqttMessageIdVariableHeader from = MqttMessageIdVariableHeader.from(messageId); - MqttPubAckMessage mqttPubAckMessage = new MqttPubAckMessage(mqttFixedHeader,from); - Channel channel = mqttChannel.getChannel(); - channel.writeAndFlush(mqttPubAckMessage); - SendMqttMessage sendMqttMessage = addQueue(channel, messageId, null, null, null, ConfirmStatus.PUBREC); - mqttChannel.addSendMqttMessage(messageId,sendMqttMessage); - } - - /** - * 发送qos2 publish 确认消息 第二步 - */ - protected void sendPubRel(Channel channel,boolean isDup,int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBREL,isDup, MqttQoS.AT_LEAST_ONCE,false,0x02); - MqttMessageIdVariableHeader from = MqttMessageIdVariableHeader.from(messageId); - MqttPubAckMessage mqttPubAckMessage = new MqttPubAckMessage(mqttFixedHeader,from); - channel.writeAndFlush(mqttPubAckMessage); - } - - /** - * 发送qos2 publish 确认消息 第三步 - */ - protected void sendToPubComp(Channel channel,int messageId){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP,false, MqttQoS.AT_MOST_ONCE,false,0x02); - MqttMessageIdVariableHeader from = MqttMessageIdVariableHeader.from(messageId); - MqttPubAckMessage mqttPubAckMessage = new MqttPubAckMessage(mqttFixedHeader,from); - channel.writeAndFlush(mqttPubAckMessage); - } - - private SendMqttMessage addQueue(Channel channel,int messageId,String topic,byte[] datas,MqttQoS mqttQoS,ConfirmStatus confirmStatus){ - SendMqttMessage build = SendMqttMessage.builder(). - channel(channel). - confirmStatus(confirmStatus). - messageId(messageId) - .topic(topic) - .qos(mqttQoS) - .byteBuf(datas) - .time(System.currentTimeMillis()).build(); - scanRunnable.addQueue(build); - return build; - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/WillService.java b/src/main/java/com/myself/nettychat/bootstrap/channel/WillService.java deleted file mode 100644 index 3aa4213..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/WillService.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.myself.nettychat.bootstrap.channel; - -import com.myself.nettychat.bootstrap.BaseApi; -import com.myself.nettychat.bootstrap.ChannelService; -import com.myself.nettychat.bootstrap.bean.WillMeaasge; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.concurrent.ConcurrentHashMap; - -@Slf4j -@Component -@Data -@NoArgsConstructor -public class WillService implements BaseApi { - - @Autowired - ChannelService channelService; - - private static ConcurrentHashMap willMeaasges = new ConcurrentHashMap<>(); // deviceid -WillMeaasge - - - - /** - * 保存遗嘱消息 - */ - public void save(String deviceid, WillMeaasge build) { - willMeaasges.put(deviceid,build); // 替换旧的 - } - - - public void doSend( String deviceId) { // 客户端断开连接后 开启遗嘱消息发送 - if(StringUtils.isNotBlank(deviceId)&&(willMeaasges.get(deviceId))!=null){ - WillMeaasge willMeaasge = willMeaasges.get(deviceId); - channelService.sendWillMsg(willMeaasge); // 发送遗嘱消息 - if(!willMeaasge.isRetain()){ // 移除 - willMeaasges.remove(deviceId); - log.info("deviceId will message["+willMeaasge.getWillMessage()+"] is removed"); - } - } - } - - /** - * 删除遗嘱消息 - */ - public void del(String deviceid ) {willMeaasges.remove(deviceid);} - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/channel/cache/CacheMap.java b/src/main/java/com/myself/nettychat/bootstrap/channel/cache/CacheMap.java deleted file mode 100644 index 68f805e..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/channel/cache/CacheMap.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.myself.nettychat.bootstrap.channel.cache; - -import lombok.extern.slf4j.Slf4j; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -/** - * @author MySelf - * @create 2018/9/22 - * @desc 缓存操作 - **/ -@Slf4j -public class CacheMap { - - private ConcurrentHashMap> datas = new ConcurrentHashMap<>(); - - public boolean putData(K[] topic, V v){ - if(topic.length==1){ - Node kvNode = buildOne(topic[0], v); - if(kvNode!=null && kvNode.topic.equals(topic[0])){ - return true; - } - } - else{ - Node kvNode = buildOne(topic[0], null); - for(int i=1;i kvNode = datas.get(ks[0]); - for(int i=1;i getData(K[] ks){ - if(ks.length==1){ - return datas.get(ks[0]).get(); - } - else{ - Node node = datas.get(ks[0]); - if(node!=null){ - List all = new ArrayList<>(); - all.addAll(node.get()); - for(int i=1;i buildOne(K k,V v){ - - Node node = this.datas.computeIfAbsent(k, key -> { - Node kObjectNode = new Node<>(k); - return kObjectNode; - }); - if(v!=null){ - node.put(v); - } - return node; - } - - - - class Node{ - - private final K topic; - - - private volatile ConcurrentHashMap> map =new ConcurrentHashMap<>() ; - - - List vs = new CopyOnWriteArrayList<>(); - - - public K getTopic() {return topic;} - - Node(K topic) { - this.topic = topic; - } - - public boolean delValue(V v){ - return vs.remove(v); - } - - public Node putNextValue(K k,V v){ - Node kvNode = map.computeIfAbsent(k, key -> { - Node node = new Node<>(k); - return node; - }); - if(v!=null){ - kvNode.put(v); - } - return kvNode; - } - - - public Node getNext(K k){ - return map.get(k); - } - - - public boolean put(V v){ - return vs.add(v); - } - - - public List get(){ - return vs; - } - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/coder/ByteBufToWebSocketFrameEncoder.java b/src/main/java/com/myself/nettychat/bootstrap/coder/ByteBufToWebSocketFrameEncoder.java deleted file mode 100644 index 6c34606..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/coder/ByteBufToWebSocketFrameEncoder.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.myself.nettychat.bootstrap.coder; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToMessageEncoder; -import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; - -import java.util.List; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 转换 - **/ -public class ByteBufToWebSocketFrameEncoder extends MessageToMessageEncoder { - - @Override - protected void encode(ChannelHandlerContext ctx, ByteBuf byteBuf, List out) throws Exception { - if (byteBuf == null) { - return; - } - BinaryWebSocketFrame result = new BinaryWebSocketFrame(); - result.content().writeBytes(byteBuf); - out.add(result); - } -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/coder/WebSocketFrameToByteBufDecoder.java b/src/main/java/com/myself/nettychat/bootstrap/coder/WebSocketFrameToByteBufDecoder.java deleted file mode 100644 index 032d657..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/coder/WebSocketFrameToByteBufDecoder.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.myself.nettychat.bootstrap.coder; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToMessageDecoder; -import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; - -import java.util.List; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 转换 - **/ -public class WebSocketFrameToByteBufDecoder extends MessageToMessageDecoder { - - - @Override - protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame wsFrame, List out) throws Exception { - ByteBuf buf = wsFrame.content(); - //避免计数器为0,报错 - buf.retain(); - out.add(buf); - } -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/handler/DefaultMqttHandler.java b/src/main/java/com/myself/nettychat/bootstrap/handler/DefaultMqttHandler.java deleted file mode 100644 index 8c4fbee..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/handler/DefaultMqttHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.myself.nettychat.bootstrap.handler; - -import com.myself.nettychat.bootstrap.ChannelService; -import com.myself.nettychat.bootstrap.bean.MqttChannel; -import com.myself.nettychat.common.mqtts.MqttHandlerIntf; -import com.myself.nettychat.common.mqtts.MqttHander; -import com.myself.nettychat.common.mqtts.ServerMqttHandlerService; -import com.myself.nettychat.common.exception.NoFindHandlerException; -import io.netty.channel.Channel; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.mqtt.*; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 默认MQTTHandler处理 - **/ -@Slf4j -@Component -@ChannelHandler.Sharable -public class DefaultMqttHandler extends MqttHander { - - private final MqttHandlerIntf mqttHandlerApi; - - @Autowired - ChannelService channelService; - - - public DefaultMqttHandler(MqttHandlerIntf mqttHandlerApi) { - super(mqttHandlerApi); - this.mqttHandlerApi = mqttHandlerApi; - } - - @Override - public void doMessage(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) { - Channel channel = channelHandlerContext.channel(); - ServerMqttHandlerService serverMqttHandlerService; - if(mqttHandlerApi instanceof ServerMqttHandlerService){ - serverMqttHandlerService =(ServerMqttHandlerService)mqttHandlerApi; - } - else{ - throw new NoFindHandlerException("server handler 不匹配"); - } - MqttFixedHeader mqttFixedHeader = mqttMessage.fixedHeader(); - if(mqttFixedHeader.messageType().equals(MqttMessageType.CONNECT)){ - if(!serverMqttHandlerService.login(channel, (MqttConnectMessage) mqttMessage)){ - channel.close(); - } - return ; - } - MqttChannel mqttChannel = channelService.getMqttChannel(channelService.getDeviceId(channel)); - if(mqttChannel!=null && mqttChannel.isLogin()){ - switch (mqttFixedHeader.messageType()){ - case PUBLISH: - serverMqttHandlerService.publish(channel, (MqttPublishMessage) mqttMessage); - break; - case SUBSCRIBE: - serverMqttHandlerService.subscribe(channel, (MqttSubscribeMessage) mqttMessage); - break; - case PINGREQ: - serverMqttHandlerService.pong(channel); - break; - case DISCONNECT: - serverMqttHandlerService.disconnect(channel); - break; - case UNSUBSCRIBE: - serverMqttHandlerService.unsubscribe(channel,(MqttUnsubscribeMessage)mqttMessage); - break; - case PUBACK: - mqttHandlerApi.puback(channel,mqttMessage); - break; - case PUBREC: - mqttHandlerApi.pubrec(channel,mqttMessage); - break; - case PUBREL: - mqttHandlerApi.pubrel(channel,mqttMessage); - break; - case PUBCOMP: - mqttHandlerApi.pubcomp(channel,mqttMessage); - break; - default: - break; - } - } - } - - - - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - log.info("【DefaultMqttHandler:channelActive】"+ctx.channel().remoteAddress().toString()+"链接成功"); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - log.error("exception",cause); - mqttHandlerApi.close(ctx.channel()); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/scan/SacnScheduled.java b/src/main/java/com/myself/nettychat/bootstrap/scan/SacnScheduled.java deleted file mode 100644 index 15cc0ce..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/scan/SacnScheduled.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.myself.nettychat.bootstrap.scan; - -import com.myself.nettychat.bootstrap.bean.SendMqttMessage; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import lombok.extern.slf4j.Slf4j; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 扫描消息确认 - **/ -@Slf4j -public class SacnScheduled extends ScanRunnable { - - private final long time; - - public SacnScheduled(long time) { - this.time = time; - } - - private boolean checkTime(long time) { - return System.currentTimeMillis()-time>=10*1000; - } - - @Override - public void doInfo(SendMqttMessage poll) { - if(checkTime(poll.getTime()) && poll.getChannel().isActive()){ - poll.setTime(System.currentTimeMillis()); - switch (poll.getConfirmStatus()){ - case PUB: - pubMessage(poll.getChannel(),poll); - break; - case PUBREL: - sendAck(MqttMessageType.PUBREL,poll); - break; - case PUBREC: - sendAck(MqttMessageType.PUBREC,poll); - break; - } - } - } - - private void pubMessage(Channel channel, SendMqttMessage mqttMessage){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,true, mqttMessage.getQos(),mqttMessage.isRetain(),0); - MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(mqttMessage.getTopic(),mqttMessage.getMessageId()); - MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader,mqttPublishVariableHeader, Unpooled.wrappedBuffer(mqttMessage.getByteBuf())); - channel.writeAndFlush(mqttPublishMessage); - } - - protected void sendAck(MqttMessageType type,SendMqttMessage mqttMessage){ - MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(type,true, MqttQoS.AT_LEAST_ONCE,false,0x02); - MqttMessageIdVariableHeader from = MqttMessageIdVariableHeader.from(mqttMessage.getMessageId()); - MqttPubAckMessage mqttPubAckMessage = new MqttPubAckMessage(mqttFixedHeader,from); - mqttMessage.getChannel().writeAndFlush(mqttPubAckMessage); - } - -} diff --git a/src/main/java/com/myself/nettychat/bootstrap/scan/ScanRunnable.java b/src/main/java/com/myself/nettychat/bootstrap/scan/ScanRunnable.java deleted file mode 100644 index 4d4cc8c..0000000 --- a/src/main/java/com/myself/nettychat/bootstrap/scan/ScanRunnable.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.myself.nettychat.bootstrap.scan; - -import com.myself.nettychat.bootstrap.bean.SendMqttMessage; -import lombok.extern.slf4j.Slf4j; -import com.myself.nettychat.common.enums.ConfirmStatus; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 扫描未确认的消息 - **/ -@Slf4j -public abstract class ScanRunnable implements Runnable{ - - LinkedBlockingQueue queue =new LinkedBlockingQueue(); - - public boolean addQueue(SendMqttMessage t){ - return queue.add(t); - } - - public boolean addQueues(List ts){ - return queue.addAll(ts); - } - - - @Override - public void run() { - for(;;){ - try { - SendMqttMessage poll= queue.take(); - if(poll.getConfirmStatus()!= ConfirmStatus.COMPLETE){ - doInfo(poll); - queue.offer(poll); - } - } catch (InterruptedException e) { - log.error("scan InterruptedException",e); - } - } - } - public abstract void doInfo( SendMqttMessage poll); - -} diff --git a/src/main/java/com/myself/nettychat/common/enums/ConfirmStatus.java b/src/main/java/com/myself/nettychat/common/enums/ConfirmStatus.java deleted file mode 100644 index 968b807..0000000 --- a/src/main/java/com/myself/nettychat/common/enums/ConfirmStatus.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.myself.nettychat.common.enums; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 确认状态 - **/ -public enum ConfirmStatus { - PUB, - PUBREC, - PUBREL, - COMPLETE, -} diff --git a/src/main/java/com/myself/nettychat/common/enums/ProtocolEnum.java b/src/main/java/com/myself/nettychat/common/enums/ProtocolEnum.java deleted file mode 100644 index 19855ea..0000000 --- a/src/main/java/com/myself/nettychat/common/enums/ProtocolEnum.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.myself.nettychat.common.enums; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 协议 - **/ -public enum ProtocolEnum { - MQTT, - - MQTT_WS_MQTT, - - MQTT_WS_PAHO, -} diff --git a/src/main/java/com/myself/nettychat/common/enums/QosStatus.java b/src/main/java/com/myself/nettychat/common/enums/QosStatus.java deleted file mode 100644 index 0a3643a..0000000 --- a/src/main/java/com/myself/nettychat/common/enums/QosStatus.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.myself.nettychat.common.enums; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc Qos确认状态 - **/ -public enum QosStatus { - - PUBD, // 已发送 没收到RECD (发送) - - RECD, //publish 推送回复过(发送) - -} diff --git a/src/main/java/com/myself/nettychat/common/enums/SessionStatus.java b/src/main/java/com/myself/nettychat/common/enums/SessionStatus.java deleted file mode 100644 index 593d63f..0000000 --- a/src/main/java/com/myself/nettychat/common/enums/SessionStatus.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.myself.nettychat.common.enums; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc Channel 会话状态 - **/ -public enum SessionStatus { - - OPEN, - CLOSE - -} diff --git a/src/main/java/com/myself/nettychat/common/enums/SubStatus.java b/src/main/java/com/myself/nettychat/common/enums/SubStatus.java deleted file mode 100644 index 2ab833c..0000000 --- a/src/main/java/com/myself/nettychat/common/enums/SubStatus.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.myself.nettychat.common.enums; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 是否订阅过主题 - **/ -public enum SubStatus { - YES, - NO -} diff --git a/src/main/java/com/myself/nettychat/common/mqtts/ClientMqttHandlerService.java b/src/main/java/com/myself/nettychat/common/mqtts/ClientMqttHandlerService.java deleted file mode 100644 index 56f9fda..0000000 --- a/src/main/java/com/myself/nettychat/common/mqtts/ClientMqttHandlerService.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.myself.nettychat.common.mqtts; - -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import io.netty.handler.timeout.IdleStateEvent; - - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 抽象出客户端的事件 - **/ -public abstract class ClientMqttHandlerService implements MqttHandlerIntf { - - @Override - public void doTimeOut(Channel channel, IdleStateEvent evt) { - heart(channel,evt); - } - - public abstract void heart(Channel channel, IdleStateEvent evt); - - public abstract void suback(Channel channel,MqttSubAckMessage mqttMessage) ; - - public abstract void pubBackMessage(Channel channel, int i); - - public abstract void unsubBack(Channel channel, MqttMessage mqttMessage); -} diff --git a/src/main/java/com/myself/nettychat/common/mqtts/MqttHander.java b/src/main/java/com/myself/nettychat/common/mqtts/MqttHander.java deleted file mode 100644 index 061dd77..0000000 --- a/src/main/java/com/myself/nettychat/common/mqtts/MqttHander.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.myself.nettychat.common.mqtts; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.mqtt.MqttFixedHeader; -import io.netty.handler.codec.mqtt.MqttMessage; -import io.netty.handler.timeout.IdleStateEvent; -import lombok.extern.slf4j.Slf4j; - -import java.util.Optional; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc mtqq协议处理器 - **/ -@Slf4j -public abstract class MqttHander extends SimpleChannelInboundHandler { - - MqttHandlerIntf mqttHandlerApi; - - public MqttHander(MqttHandlerIntf mqttHandlerIntf){ - this.mqttHandlerApi=mqttHandlerIntf; - } - - @Override - protected void channelRead0(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) throws Exception { - MqttFixedHeader mqttFixedHeader = mqttMessage.fixedHeader(); - Optional.ofNullable(mqttFixedHeader) - .ifPresent(mqttFixedHeader1 -> doMessage(channelHandlerContext,mqttMessage)); - } - - - public abstract void doMessage(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage); - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - log.info("【DefaultMqttHandler:channelInactive】"+ctx.channel().localAddress().toString()+"关闭成功"); - mqttHandlerApi.close(ctx.channel()); - } - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - if(evt instanceof IdleStateEvent){ - mqttHandlerApi.doTimeOut(ctx.channel(),(IdleStateEvent)evt); - } - super.userEventTriggered(ctx, evt); - } - -} diff --git a/src/main/java/com/myself/nettychat/common/mqtts/MqttHandlerIntf.java b/src/main/java/com/myself/nettychat/common/mqtts/MqttHandlerIntf.java deleted file mode 100644 index 4f274ee..0000000 --- a/src/main/java/com/myself/nettychat/common/mqtts/MqttHandlerIntf.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.myself.nettychat.common.mqtts; - -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.MqttMessage; -import io.netty.handler.timeout.IdleStateEvent; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 自定义 对外暴露,消息处理API - **/ -public interface MqttHandlerIntf { - - void close(Channel channel); - - void puback(Channel channel, MqttMessage mqttMessage); - - void pubrec(Channel channel, MqttMessage mqttMessage); - - void pubrel(Channel channel, MqttMessage mqttMessage); - - void pubcomp(Channel channel, MqttMessage mqttMessage); - - void doTimeOut(Channel channel, IdleStateEvent evt); - -} diff --git a/src/main/java/com/myself/nettychat/common/mqtts/ServerMqttHandlerService.java b/src/main/java/com/myself/nettychat/common/mqtts/ServerMqttHandlerService.java deleted file mode 100644 index fd62ee5..0000000 --- a/src/main/java/com/myself/nettychat/common/mqtts/ServerMqttHandlerService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.myself.nettychat.common.mqtts; - -import io.netty.channel.Channel; -import io.netty.handler.codec.mqtt.*; -import io.netty.handler.timeout.IdleStateEvent; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 抽象出服务端的事件 - **/ -public abstract class ServerMqttHandlerService implements MqttHandlerIntf { - - public abstract boolean login(Channel channel, MqttConnectMessage mqttConnectMessage); - - public abstract void publish(Channel channel, MqttPublishMessage mqttPublishMessage); - - public abstract void subscribe(Channel channel, MqttSubscribeMessage mqttSubscribeMessage); - - public abstract void pong(Channel channel); - - public abstract void unsubscribe(Channel channel, MqttUnsubscribeMessage mqttMessage); - - public abstract void disconnect(Channel channel); - - public abstract void doTimeOut(Channel channel, IdleStateEvent evt); - -} diff --git a/src/main/java/com/myself/nettychat/common/properties/InitNetty.java b/src/main/java/com/myself/nettychat/common/properties/InitNetty.java index ab6ad0c..25efbad 100644 --- a/src/main/java/com/myself/nettychat/common/properties/InitNetty.java +++ b/src/main/java/com/myself/nettychat/common/properties/InitNetty.java @@ -3,8 +3,6 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; -import com.myself.nettychat.common.enums.ProtocolEnum; -import com.myself.nettychat.common.mqtts.MqttHander; /** * @Author:UncleCatMySelf @@ -13,10 +11,10 @@ * @Date:Created in 10:54 2018\8\14 0014 */ @Data +@Component @ConfigurationProperties(prefix = "netty") public class InitNetty { - private ProtocolEnum protocol; private int webport; @@ -52,7 +50,6 @@ public class InitNetty { private String jksCertificatePassword; - private Class mqttHander ; private int initalDelay ; diff --git a/src/main/java/com/myself/nettychat/common/ssl/SecureSocketKeyStore.java b/src/main/java/com/myself/nettychat/common/ssl/SecureSocketKeyStore.java deleted file mode 100644 index 3bae691..0000000 --- a/src/main/java/com/myself/nettychat/common/ssl/SecureSocketKeyStore.java +++ /dev/null @@ -1,456 +0,0 @@ -package com.myself.nettychat.common.ssl; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.KeyStore; - -/** - * A bogus key store which provides all the required information to create an - * example SSL connection. - * - * To generate a bogus key store: - * - *
- * keytool -genkey -alias securesocket \ -keysize 2048 -validity 36500 \  -keyalg RSA -dname "CN=securesocket" \   -keypass inc0rrect -storepass mu$tch8ng3 \  -keystore cert.jks
- *
- *
- *
- *
- * 
- */ -public class SecureSocketKeyStore { - - private static final byte[] CERT_BYTES = { (byte) 254, (byte) 237, - (byte) 254, (byte) 237, (byte) 0, (byte) 0, (byte) 0, (byte) 2, - (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 0, (byte) 0, - (byte) 0, (byte) 1, (byte) 0, (byte) 12, (byte) 115, (byte) 101, - (byte) 99, (byte) 117, (byte) 114, (byte) 101, (byte) 115, - (byte) 111, (byte) 99, (byte) 107, (byte) 101, (byte) 116, - (byte) 0, (byte) 0, (byte) 1, (byte) 69, (byte) 231, (byte) 201, - (byte) 156, (byte) 140, (byte) 0, (byte) 0, (byte) 5, (byte) 0, - (byte) 48, (byte) 130, (byte) 4, (byte) 252, (byte) 48, (byte) 14, - (byte) 6, (byte) 10, (byte) 43, (byte) 6, (byte) 1, (byte) 4, - (byte) 1, (byte) 42, (byte) 2, (byte) 17, (byte) 1, (byte) 1, - (byte) 5, (byte) 0, (byte) 4, (byte) 130, (byte) 4, (byte) 232, - (byte) 221, (byte) 18, (byte) 203, (byte) 171, (byte) 175, - (byte) 82, (byte) 132, (byte) 227, (byte) 115, (byte) 143, - (byte) 38, (byte) 191, (byte) 42, (byte) 202, (byte) 130, - (byte) 171, (byte) 75, (byte) 6, (byte) 161, (byte) 120, - (byte) 204, (byte) 61, (byte) 106, (byte) 160, (byte) 81, (byte) 9, - (byte) 204, (byte) 153, (byte) 166, (byte) 38, (byte) 246, - (byte) 13, (byte) 43, (byte) 19, (byte) 100, (byte) 132, (byte) 45, - (byte) 90, (byte) 143, (byte) 1, (byte) 231, (byte) 182, (byte) 89, - (byte) 228, (byte) 183, (byte) 17, (byte) 95, (byte) 129, - (byte) 229, (byte) 42, (byte) 182, (byte) 126, (byte) 114, - (byte) 76, (byte) 124, (byte) 123, (byte) 246, (byte) 152, - (byte) 0, (byte) 141, (byte) 212, (byte) 111, (byte) 52, - (byte) 243, (byte) 112, (byte) 31, (byte) 117, (byte) 124, - (byte) 142, (byte) 24, (byte) 59, (byte) 198, (byte) 164, - (byte) 253, (byte) 21, (byte) 177, (byte) 189, (byte) 74, - (byte) 218, (byte) 110, (byte) 83, (byte) 154, (byte) 49, - (byte) 186, (byte) 159, (byte) 173, (byte) 202, (byte) 94, - (byte) 174, (byte) 183, (byte) 223, (byte) 119, (byte) 109, - (byte) 110, (byte) 72, (byte) 93, (byte) 208, (byte) 195, - (byte) 19, (byte) 89, (byte) 33, (byte) 34, (byte) 186, (byte) 12, - (byte) 86, (byte) 156, (byte) 156, (byte) 210, (byte) 111, - (byte) 110, (byte) 44, (byte) 106, (byte) 36, (byte) 67, - (byte) 168, (byte) 7, (byte) 179, (byte) 244, (byte) 53, - (byte) 134, (byte) 10, (byte) 86, (byte) 179, (byte) 34, (byte) 60, - (byte) 184, (byte) 179, (byte) 162, (byte) 69, (byte) 24, - (byte) 168, (byte) 100, (byte) 183, (byte) 206, (byte) 64, - (byte) 4, (byte) 32, (byte) 66, (byte) 237, (byte) 228, (byte) 92, - (byte) 6, (byte) 213, (byte) 141, (byte) 147, (byte) 198, - (byte) 141, (byte) 216, (byte) 41, (byte) 0, (byte) 101, (byte) 65, - (byte) 41, (byte) 185, (byte) 128, (byte) 229, (byte) 107, - (byte) 25, (byte) 89, (byte) 148, (byte) 16, (byte) 194, - (byte) 101, (byte) 100, (byte) 243, (byte) 147, (byte) 77, - (byte) 230, (byte) 11, (byte) 151, (byte) 99, (byte) 124, - (byte) 55, (byte) 195, (byte) 185, (byte) 30, (byte) 234, - (byte) 83, (byte) 61, (byte) 109, (byte) 131, (byte) 156, - (byte) 244, (byte) 133, (byte) 66, (byte) 39, (byte) 153, (byte) 9, - (byte) 34, (byte) 218, (byte) 201, (byte) 143, (byte) 190, - (byte) 127, (byte) 119, (byte) 102, (byte) 6, (byte) 83, - (byte) 134, (byte) 96, (byte) 170, (byte) 79, (byte) 196, - (byte) 214, (byte) 47, (byte) 215, (byte) 37, (byte) 250, - (byte) 64, (byte) 8, (byte) 165, (byte) 203, (byte) 44, (byte) 53, - (byte) 113, (byte) 147, (byte) 251, (byte) 29, (byte) 26, - (byte) 38, (byte) 193, (byte) 11, (byte) 223, (byte) 212, - (byte) 114, (byte) 96, (byte) 162, (byte) 39, (byte) 48, - (byte) 200, (byte) 172, (byte) 182, (byte) 254, (byte) 180, - (byte) 198, (byte) 11, (byte) 128, (byte) 75, (byte) 74, (byte) 93, - (byte) 226, (byte) 157, (byte) 80, (byte) 14, (byte) 9, (byte) 217, - (byte) 236, (byte) 205, (byte) 153, (byte) 35, (byte) 242, - (byte) 130, (byte) 140, (byte) 25, (byte) 16, (byte) 156, - (byte) 247, (byte) 230, (byte) 5, (byte) 247, (byte) 0, (byte) 34, - (byte) 196, (byte) 15, (byte) 118, (byte) 255, (byte) 185, - (byte) 199, (byte) 59, (byte) 99, (byte) 27, (byte) 187, (byte) 83, - (byte) 81, (byte) 12, (byte) 71, (byte) 69, (byte) 127, (byte) 130, - (byte) 164, (byte) 97, (byte) 195, (byte) 216, (byte) 215, - (byte) 61, (byte) 29, (byte) 196, (byte) 62, (byte) 160, - (byte) 188, (byte) 209, (byte) 173, (byte) 230, (byte) 0, - (byte) 204, (byte) 225, (byte) 1, (byte) 5, (byte) 42, (byte) 223, - (byte) 232, (byte) 187, (byte) 190, (byte) 67, (byte) 126, - (byte) 235, (byte) 178, (byte) 218, (byte) 179, (byte) 46, - (byte) 186, (byte) 156, (byte) 186, (byte) 6, (byte) 191, - (byte) 68, (byte) 239, (byte) 31, (byte) 16, (byte) 204, (byte) 24, - (byte) 68, (byte) 164, (byte) 88, (byte) 10, (byte) 174, (byte) 26, - (byte) 54, (byte) 187, (byte) 149, (byte) 132, (byte) 128, - (byte) 173, (byte) 165, (byte) 8, (byte) 69, (byte) 96, (byte) 49, - (byte) 57, (byte) 223, (byte) 110, (byte) 29, (byte) 215, - (byte) 98, (byte) 42, (byte) 15, (byte) 153, (byte) 228, - (byte) 216, (byte) 61, (byte) 160, (byte) 230, (byte) 34, - (byte) 40, (byte) 232, (byte) 136, (byte) 139, (byte) 140, - (byte) 236, (byte) 251, (byte) 119, (byte) 242, (byte) 199, - (byte) 167, (byte) 61, (byte) 141, (byte) 89, (byte) 29, (byte) 82, - (byte) 114, (byte) 229, (byte) 198, (byte) 27, (byte) 133, - (byte) 87, (byte) 0, (byte) 53, (byte) 69, (byte) 42, (byte) 91, - (byte) 174, (byte) 82, (byte) 244, (byte) 160, (byte) 82, - (byte) 142, (byte) 221, (byte) 106, (byte) 151, (byte) 241, - (byte) 214, (byte) 64, (byte) 14, (byte) 28, (byte) 2, (byte) 3, - (byte) 145, (byte) 143, (byte) 18, (byte) 165, (byte) 247, - (byte) 178, (byte) 211, (byte) 16, (byte) 222, (byte) 76, - (byte) 60, (byte) 119, (byte) 130, (byte) 199, (byte) 230, - (byte) 229, (byte) 3, (byte) 22, (byte) 100, (byte) 135, - (byte) 103, (byte) 60, (byte) 181, (byte) 191, (byte) 56, - (byte) 249, (byte) 181, (byte) 169, (byte) 210, (byte) 25, - (byte) 152, (byte) 201, (byte) 226, (byte) 119, (byte) 71, - (byte) 204, (byte) 70, (byte) 220, (byte) 103, (byte) 46, - (byte) 166, (byte) 125, (byte) 40, (byte) 86, (byte) 208, - (byte) 114, (byte) 138, (byte) 24, (byte) 27, (byte) 219, - (byte) 123, (byte) 161, (byte) 52, (byte) 14, (byte) 38, - (byte) 244, (byte) 112, (byte) 238, (byte) 121, (byte) 90, - (byte) 34, (byte) 157, (byte) 131, (byte) 53, (byte) 245, - (byte) 162, (byte) 89, (byte) 188, (byte) 6, (byte) 202, - (byte) 164, (byte) 130, (byte) 34, (byte) 232, (byte) 74, - (byte) 45, (byte) 137, (byte) 164, (byte) 200, (byte) 197, - (byte) 247, (byte) 64, (byte) 110, (byte) 122, (byte) 49, - (byte) 116, (byte) 137, (byte) 253, (byte) 170, (byte) 232, - (byte) 120, (byte) 26, (byte) 171, (byte) 228, (byte) 229, - (byte) 49, (byte) 56, (byte) 56, (byte) 106, (byte) 110, (byte) 12, - (byte) 109, (byte) 93, (byte) 105, (byte) 241, (byte) 196, - (byte) 11, (byte) 18, (byte) 89, (byte) 108, (byte) 146, - (byte) 224, (byte) 161, (byte) 181, (byte) 236, (byte) 74, - (byte) 128, (byte) 24, (byte) 239, (byte) 22, (byte) 146, (byte) 0, - (byte) 69, (byte) 182, (byte) 246, (byte) 43, (byte) 59, - (byte) 208, (byte) 33, (byte) 48, (byte) 81, (byte) 0, (byte) 70, - (byte) 225, (byte) 222, (byte) 122, (byte) 178, (byte) 138, - (byte) 12, (byte) 207, (byte) 233, (byte) 164, (byte) 13, - (byte) 176, (byte) 123, (byte) 95, (byte) 68, (byte) 238, - (byte) 134, (byte) 66, (byte) 95, (byte) 194, (byte) 192, - (byte) 225, (byte) 244, (byte) 14, (byte) 78, (byte) 53, - (byte) 189, (byte) 217, (byte) 229, (byte) 203, (byte) 192, - (byte) 34, (byte) 38, (byte) 169, (byte) 63, (byte) 239, - (byte) 128, (byte) 172, (byte) 143, (byte) 75, (byte) 7, - (byte) 237, (byte) 125, (byte) 179, (byte) 235, (byte) 229, - (byte) 98, (byte) 8, (byte) 211, (byte) 237, (byte) 116, (byte) 75, - (byte) 27, (byte) 211, (byte) 131, (byte) 245, (byte) 89, - (byte) 150, (byte) 35, (byte) 49, (byte) 207, (byte) 113, - (byte) 237, (byte) 114, (byte) 125, (byte) 134, (byte) 191, - (byte) 110, (byte) 30, (byte) 119, (byte) 131, (byte) 175, - (byte) 166, (byte) 201, (byte) 255, (byte) 200, (byte) 1, - (byte) 126, (byte) 163, (byte) 172, (byte) 52, (byte) 118, - (byte) 184, (byte) 221, (byte) 165, (byte) 167, (byte) 165, - (byte) 20, (byte) 135, (byte) 32, (byte) 222, (byte) 188, - (byte) 250, (byte) 64, (byte) 161, (byte) 67, (byte) 236, - (byte) 212, (byte) 131, (byte) 44, (byte) 32, (byte) 70, (byte) 0, - (byte) 24, (byte) 178, (byte) 83, (byte) 155, (byte) 145, - (byte) 136, (byte) 131, (byte) 120, (byte) 181, (byte) 164, - (byte) 155, (byte) 172, (byte) 41, (byte) 213, (byte) 164, - (byte) 98, (byte) 169, (byte) 152, (byte) 184, (byte) 170, - (byte) 107, (byte) 7, (byte) 21, (byte) 228, (byte) 175, - (byte) 192, (byte) 238, (byte) 68, (byte) 197, (byte) 119, - (byte) 228, (byte) 225, (byte) 156, (byte) 235, (byte) 241, - (byte) 172, (byte) 171, (byte) 236, (byte) 128, (byte) 78, - (byte) 117, (byte) 152, (byte) 123, (byte) 93, (byte) 156, - (byte) 57, (byte) 238, (byte) 211, (byte) 188, (byte) 47, - (byte) 62, (byte) 45, (byte) 127, (byte) 58, (byte) 38, (byte) 29, - (byte) 131, (byte) 95, (byte) 85, (byte) 149, (byte) 112, - (byte) 215, (byte) 207, (byte) 41, (byte) 201, (byte) 30, - (byte) 149, (byte) 73, (byte) 245, (byte) 179, (byte) 176, - (byte) 246, (byte) 203, (byte) 204, (byte) 252, (byte) 13, - (byte) 98, (byte) 151, (byte) 93, (byte) 87, (byte) 241, - (byte) 166, (byte) 46, (byte) 249, (byte) 148, (byte) 49, - (byte) 141, (byte) 136, (byte) 49, (byte) 77, (byte) 250, - (byte) 191, (byte) 157, (byte) 90, (byte) 84, (byte) 51, - (byte) 129, (byte) 133, (byte) 66, (byte) 253, (byte) 99, - (byte) 243, (byte) 34, (byte) 142, (byte) 197, (byte) 4, - (byte) 126, (byte) 7, (byte) 217, (byte) 126, (byte) 205, - (byte) 250, (byte) 141, (byte) 231, (byte) 225, (byte) 203, - (byte) 171, (byte) 246, (byte) 201, (byte) 48, (byte) 96, - (byte) 207, (byte) 74, (byte) 253, (byte) 120, (byte) 114, - (byte) 163, (byte) 192, (byte) 24, (byte) 12, (byte) 10, - (byte) 210, (byte) 94, (byte) 136, (byte) 152, (byte) 185, - (byte) 109, (byte) 87, (byte) 35, (byte) 159, (byte) 238, - (byte) 122, (byte) 200, (byte) 107, (byte) 103, (byte) 243, - (byte) 250, (byte) 152, (byte) 68, (byte) 66, (byte) 170, (byte) 0, - (byte) 134, (byte) 229, (byte) 168, (byte) 182, (byte) 30, - (byte) 89, (byte) 240, (byte) 121, (byte) 106, (byte) 148, - (byte) 142, (byte) 49, (byte) 242, (byte) 215, (byte) 233, - (byte) 57, (byte) 120, (byte) 204, (byte) 180, (byte) 239, - (byte) 199, (byte) 133, (byte) 255, (byte) 71, (byte) 3, - (byte) 132, (byte) 228, (byte) 110, (byte) 66, (byte) 227, - (byte) 122, (byte) 82, (byte) 118, (byte) 173, (byte) 218, - (byte) 54, (byte) 99, (byte) 167, (byte) 154, (byte) 3, (byte) 189, - (byte) 25, (byte) 123, (byte) 169, (byte) 42, (byte) 184, - (byte) 59, (byte) 36, (byte) 131, (byte) 206, (byte) 248, - (byte) 90, (byte) 32, (byte) 183, (byte) 86, (byte) 62, (byte) 149, - (byte) 107, (byte) 243, (byte) 71, (byte) 197, (byte) 124, - (byte) 155, (byte) 214, (byte) 91, (byte) 29, (byte) 81, (byte) 28, - (byte) 115, (byte) 98, (byte) 130, (byte) 184, (byte) 135, - (byte) 13, (byte) 191, (byte) 147, (byte) 43, (byte) 10, - (byte) 178, (byte) 99, (byte) 165, (byte) 210, (byte) 87, - (byte) 87, (byte) 148, (byte) 31, (byte) 198, (byte) 129, - (byte) 32, (byte) 181, (byte) 3, (byte) 144, (byte) 61, (byte) 5, - (byte) 166, (byte) 252, (byte) 73, (byte) 205, (byte) 230, - (byte) 178, (byte) 162, (byte) 46, (byte) 56, (byte) 99, (byte) 77, - (byte) 97, (byte) 236, (byte) 121, (byte) 157, (byte) 139, - (byte) 153, (byte) 217, (byte) 171, (byte) 19, (byte) 68, - (byte) 36, (byte) 14, (byte) 123, (byte) 249, (byte) 101, - (byte) 127, (byte) 184, (byte) 123, (byte) 7, (byte) 124, - (byte) 68, (byte) 98, (byte) 34, (byte) 139, (byte) 224, - (byte) 173, (byte) 246, (byte) 196, (byte) 180, (byte) 70, - (byte) 207, (byte) 168, (byte) 211, (byte) 255, (byte) 84, - (byte) 0, (byte) 174, (byte) 11, (byte) 160, (byte) 155, - (byte) 127, (byte) 228, (byte) 81, (byte) 226, (byte) 115, - (byte) 142, (byte) 200, (byte) 107, (byte) 4, (byte) 204, - (byte) 219, (byte) 192, (byte) 189, (byte) 56, (byte) 127, - (byte) 184, (byte) 187, (byte) 161, (byte) 106, (byte) 62, - (byte) 225, (byte) 211, (byte) 115, (byte) 30, (byte) 172, - (byte) 191, (byte) 66, (byte) 25, (byte) 66, (byte) 235, - (byte) 107, (byte) 41, (byte) 186, (byte) 40, (byte) 239, - (byte) 173, (byte) 11, (byte) 247, (byte) 89, (byte) 79, - (byte) 135, (byte) 86, (byte) 73, (byte) 77, (byte) 164, (byte) 34, - (byte) 109, (byte) 236, (byte) 56, (byte) 198, (byte) 141, - (byte) 87, (byte) 74, (byte) 172, (byte) 56, (byte) 24, (byte) 150, - (byte) 233, (byte) 233, (byte) 165, (byte) 122, (byte) 201, - (byte) 112, (byte) 232, (byte) 23, (byte) 12, (byte) 166, - (byte) 128, (byte) 114, (byte) 139, (byte) 207, (byte) 233, - (byte) 47, (byte) 220, (byte) 172, (byte) 175, (byte) 40, - (byte) 109, (byte) 82, (byte) 142, (byte) 130, (byte) 177, - (byte) 50, (byte) 127, (byte) 196, (byte) 106, (byte) 172, - (byte) 178, (byte) 71, (byte) 178, (byte) 204, (byte) 99, - (byte) 113, (byte) 33, (byte) 189, (byte) 188, (byte) 168, - (byte) 76, (byte) 92, (byte) 230, (byte) 211, (byte) 239, - (byte) 75, (byte) 71, (byte) 64, (byte) 197, (byte) 26, (byte) 222, - (byte) 19, (byte) 213, (byte) 161, (byte) 144, (byte) 20, - (byte) 126, (byte) 192, (byte) 156, (byte) 15, (byte) 113, - (byte) 64, (byte) 73, (byte) 7, (byte) 241, (byte) 217, (byte) 127, - (byte) 171, (byte) 199, (byte) 66, (byte) 32, (byte) 179, (byte) 4, - (byte) 181, (byte) 93, (byte) 121, (byte) 193, (byte) 10, - (byte) 169, (byte) 255, (byte) 152, (byte) 199, (byte) 95, - (byte) 177, (byte) 227, (byte) 135, (byte) 21, (byte) 64, - (byte) 203, (byte) 9, (byte) 79, (byte) 243, (byte) 114, (byte) 2, - (byte) 201, (byte) 157, (byte) 180, (byte) 52, (byte) 193, - (byte) 66, (byte) 34, (byte) 155, (byte) 52, (byte) 35, (byte) 93, - (byte) 31, (byte) 96, (byte) 77, (byte) 12, (byte) 80, (byte) 195, - (byte) 96, (byte) 247, (byte) 251, (byte) 237, (byte) 36, - (byte) 170, (byte) 7, (byte) 3, (byte) 251, (byte) 243, (byte) 47, - (byte) 180, (byte) 98, (byte) 207, (byte) 176, (byte) 106, - (byte) 237, (byte) 114, (byte) 91, (byte) 229, (byte) 56, - (byte) 94, (byte) 154, (byte) 32, (byte) 62, (byte) 240, - (byte) 132, (byte) 4, (byte) 144, (byte) 227, (byte) 140, - (byte) 137, (byte) 76, (byte) 15, (byte) 117, (byte) 82, - (byte) 223, (byte) 168, (byte) 135, (byte) 33, (byte) 91, - (byte) 173, (byte) 4, (byte) 245, (byte) 192, (byte) 95, - (byte) 135, (byte) 22, (byte) 138, (byte) 89, (byte) 1, (byte) 14, - (byte) 230, (byte) 143, (byte) 195, (byte) 93, (byte) 133, - (byte) 194, (byte) 252, (byte) 188, (byte) 31, (byte) 39, - (byte) 162, (byte) 59, (byte) 148, (byte) 219, (byte) 213, - (byte) 179, (byte) 195, (byte) 165, (byte) 67, (byte) 68, - (byte) 39, (byte) 178, (byte) 143, (byte) 192, (byte) 177, - (byte) 221, (byte) 236, (byte) 63, (byte) 40, (byte) 205, - (byte) 26, (byte) 81, (byte) 127, (byte) 5, (byte) 213, (byte) 192, - (byte) 22, (byte) 147, (byte) 98, (byte) 207, (byte) 153, (byte) 8, - (byte) 108, (byte) 75, (byte) 182, (byte) 148, (byte) 0, - (byte) 151, (byte) 15, (byte) 178, (byte) 98, (byte) 145, - (byte) 255, (byte) 213, (byte) 142, (byte) 63, (byte) 247, - (byte) 42, (byte) 161, (byte) 246, (byte) 21, (byte) 128, - (byte) 47, (byte) 248, (byte) 217, (byte) 70, (byte) 195, - (byte) 151, (byte) 236, (byte) 73, (byte) 153, (byte) 230, - (byte) 152, (byte) 217, (byte) 12, (byte) 189, (byte) 65, - (byte) 85, (byte) 189, (byte) 204, (byte) 212, (byte) 161, - (byte) 210, (byte) 217, (byte) 74, (byte) 75, (byte) 186, - (byte) 122, (byte) 167, (byte) 149, (byte) 178, (byte) 202, - (byte) 205, (byte) 246, (byte) 225, (byte) 225, (byte) 190, - (byte) 56, (byte) 42, (byte) 162, (byte) 215, (byte) 107, - (byte) 45, (byte) 121, (byte) 235, (byte) 195, (byte) 219, - (byte) 22, (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 0, - (byte) 5, (byte) 88, (byte) 46, (byte) 53, (byte) 48, (byte) 57, - (byte) 0, (byte) 0, (byte) 2, (byte) 211, (byte) 48, (byte) 130, - (byte) 2, (byte) 207, (byte) 48, (byte) 130, (byte) 1, (byte) 183, - (byte) 160, (byte) 3, (byte) 2, (byte) 1, (byte) 2, (byte) 2, - (byte) 4, (byte) 58, (byte) 247, (byte) 71, (byte) 185, (byte) 48, - (byte) 13, (byte) 6, (byte) 9, (byte) 42, (byte) 134, (byte) 72, - (byte) 134, (byte) 247, (byte) 13, (byte) 1, (byte) 1, (byte) 11, - (byte) 5, (byte) 0, (byte) 48, (byte) 23, (byte) 49, (byte) 21, - (byte) 48, (byte) 19, (byte) 6, (byte) 3, (byte) 85, (byte) 4, - (byte) 3, (byte) 19, (byte) 12, (byte) 115, (byte) 101, (byte) 99, - (byte) 117, (byte) 114, (byte) 101, (byte) 115, (byte) 111, - (byte) 99, (byte) 107, (byte) 101, (byte) 116, (byte) 48, - (byte) 32, (byte) 23, (byte) 13, (byte) 49, (byte) 52, (byte) 48, - (byte) 53, (byte) 49, (byte) 48, (byte) 50, (byte) 48, (byte) 49, - (byte) 56, (byte) 52, (byte) 48, (byte) 90, (byte) 24, (byte) 15, - (byte) 50, (byte) 49, (byte) 49, (byte) 52, (byte) 48, (byte) 52, - (byte) 49, (byte) 54, (byte) 50, (byte) 48, (byte) 49, (byte) 56, - (byte) 52, (byte) 48, (byte) 90, (byte) 48, (byte) 23, (byte) 49, - (byte) 21, (byte) 48, (byte) 19, (byte) 6, (byte) 3, (byte) 85, - (byte) 4, (byte) 3, (byte) 19, (byte) 12, (byte) 115, (byte) 101, - (byte) 99, (byte) 117, (byte) 114, (byte) 101, (byte) 115, - (byte) 111, (byte) 99, (byte) 107, (byte) 101, (byte) 116, - (byte) 48, (byte) 130, (byte) 1, (byte) 34, (byte) 48, (byte) 13, - (byte) 6, (byte) 9, (byte) 42, (byte) 134, (byte) 72, (byte) 134, - (byte) 247, (byte) 13, (byte) 1, (byte) 1, (byte) 1, (byte) 5, - (byte) 0, (byte) 3, (byte) 130, (byte) 1, (byte) 15, (byte) 0, - (byte) 48, (byte) 130, (byte) 1, (byte) 10, (byte) 2, (byte) 130, - (byte) 1, (byte) 1, (byte) 0, (byte) 153, (byte) 113, (byte) 7, - (byte) 44, (byte) 219, (byte) 76, (byte) 101, (byte) 226, - (byte) 138, (byte) 96, (byte) 219, (byte) 60, (byte) 167, - (byte) 138, (byte) 222, (byte) 6, (byte) 78, (byte) 169, (byte) 64, - (byte) 188, (byte) 156, (byte) 190, (byte) 119, (byte) 16, - (byte) 34, (byte) 228, (byte) 250, (byte) 253, (byte) 119, - (byte) 75, (byte) 240, (byte) 60, (byte) 242, (byte) 52, - (byte) 137, (byte) 146, (byte) 20, (byte) 130, (byte) 202, - (byte) 226, (byte) 125, (byte) 19, (byte) 7, (byte) 34, (byte) 8, - (byte) 61, (byte) 243, (byte) 202, (byte) 225, (byte) 206, - (byte) 223, (byte) 53, (byte) 74, (byte) 56, (byte) 222, (byte) 47, - (byte) 99, (byte) 235, (byte) 57, (byte) 73, (byte) 90, (byte) 198, - (byte) 109, (byte) 104, (byte) 36, (byte) 255, (byte) 124, - (byte) 57, (byte) 155, (byte) 248, (byte) 120, (byte) 56, - (byte) 56, (byte) 38, (byte) 41, (byte) 216, (byte) 1, (byte) 216, - (byte) 216, (byte) 100, (byte) 239, (byte) 79, (byte) 222, - (byte) 34, (byte) 21, (byte) 182, (byte) 112, (byte) 136, - (byte) 137, (byte) 16, (byte) 141, (byte) 15, (byte) 83, (byte) 94, - (byte) 245, (byte) 36, (byte) 203, (byte) 178, (byte) 137, - (byte) 159, (byte) 86, (byte) 220, (byte) 253, (byte) 112, - (byte) 200, (byte) 50, (byte) 135, (byte) 215, (byte) 190, - (byte) 21, (byte) 186, (byte) 84, (byte) 21, (byte) 96, (byte) 126, - (byte) 253, (byte) 115, (byte) 209, (byte) 241, (byte) 94, - (byte) 115, (byte) 219, (byte) 0, (byte) 25, (byte) 253, - (byte) 209, (byte) 182, (byte) 118, (byte) 230, (byte) 10, - (byte) 50, (byte) 131, (byte) 39, (byte) 249, (byte) 136, - (byte) 11, (byte) 101, (byte) 192, (byte) 12, (byte) 210, - (byte) 179, (byte) 237, (byte) 213, (byte) 68, (byte) 101, - (byte) 58, (byte) 187, (byte) 255, (byte) 240, (byte) 164, - (byte) 147, (byte) 72, (byte) 148, (byte) 227, (byte) 155, - (byte) 88, (byte) 250, (byte) 101, (byte) 253, (byte) 87, - (byte) 140, (byte) 168, (byte) 39, (byte) 163, (byte) 133, - (byte) 150, (byte) 252, (byte) 226, (byte) 234, (byte) 52, - (byte) 88, (byte) 40, (byte) 56, (byte) 23, (byte) 105, (byte) 236, - (byte) 4, (byte) 113, (byte) 98, (byte) 4, (byte) 0, (byte) 117, - (byte) 59, (byte) 77, (byte) 236, (byte) 135, (byte) 93, (byte) 54, - (byte) 30, (byte) 6, (byte) 126, (byte) 90, (byte) 15, (byte) 105, - (byte) 89, (byte) 216, (byte) 154, (byte) 72, (byte) 134, - (byte) 209, (byte) 74, (byte) 197, (byte) 237, (byte) 51, - (byte) 37, (byte) 33, (byte) 106, (byte) 50, (byte) 71, (byte) 134, - (byte) 169, (byte) 173, (byte) 88, (byte) 111, (byte) 217, - (byte) 117, (byte) 184, (byte) 97, (byte) 1, (byte) 38, (byte) 76, - (byte) 112, (byte) 170, (byte) 190, (byte) 250, (byte) 96, - (byte) 17, (byte) 45, (byte) 117, (byte) 183, (byte) 82, - (byte) 155, (byte) 10, (byte) 53, (byte) 15, (byte) 214, (byte) 36, - (byte) 134, (byte) 249, (byte) 146, (byte) 98, (byte) 99, - (byte) 64, (byte) 158, (byte) 99, (byte) 227, (byte) 21, (byte) 92, - (byte) 98, (byte) 90, (byte) 202, (byte) 214, (byte) 134, - (byte) 233, (byte) 212, (byte) 149, (byte) 2, (byte) 3, (byte) 1, - (byte) 0, (byte) 1, (byte) 163, (byte) 33, (byte) 48, (byte) 31, - (byte) 48, (byte) 29, (byte) 6, (byte) 3, (byte) 85, (byte) 29, - (byte) 14, (byte) 4, (byte) 22, (byte) 4, (byte) 20, (byte) 115, - (byte) 110, (byte) 177, (byte) 165, (byte) 41, (byte) 26, - (byte) 142, (byte) 198, (byte) 221, (byte) 63, (byte) 79, - (byte) 252, (byte) 219, (byte) 159, (byte) 68, (byte) 102, - (byte) 76, (byte) 153, (byte) 128, (byte) 164, (byte) 48, - (byte) 13, (byte) 6, (byte) 9, (byte) 42, (byte) 134, (byte) 72, - (byte) 134, (byte) 247, (byte) 13, (byte) 1, (byte) 1, (byte) 11, - (byte) 5, (byte) 0, (byte) 3, (byte) 130, (byte) 1, (byte) 1, - (byte) 0, (byte) 118, (byte) 55, (byte) 245, (byte) 122, - (byte) 159, (byte) 155, (byte) 98, (byte) 122, (byte) 229, - (byte) 186, (byte) 23, (byte) 207, (byte) 109, (byte) 225, - (byte) 220, (byte) 74, (byte) 51, (byte) 218, (byte) 10, - (byte) 115, (byte) 137, (byte) 103, (byte) 127, (byte) 28, - (byte) 30, (byte) 184, (byte) 149, (byte) 249, (byte) 193, - (byte) 206, (byte) 208, (byte) 181, (byte) 191, (byte) 128, - (byte) 18, (byte) 208, (byte) 24, (byte) 132, (byte) 147, - (byte) 184, (byte) 198, (byte) 82, (byte) 204, (byte) 183, - (byte) 127, (byte) 87, (byte) 234, (byte) 136, (byte) 197, - (byte) 34, (byte) 232, (byte) 124, (byte) 210, (byte) 2, - (byte) 192, (byte) 69, (byte) 246, (byte) 25, (byte) 232, - (byte) 162, (byte) 0, (byte) 157, (byte) 216, (byte) 194, - (byte) 26, (byte) 207, (byte) 225, (byte) 169, (byte) 59, - (byte) 246, (byte) 52, (byte) 51, (byte) 150, (byte) 210, - (byte) 50, (byte) 118, (byte) 58, (byte) 154, (byte) 45, - (byte) 128, (byte) 138, (byte) 47, (byte) 174, (byte) 83, - (byte) 117, (byte) 18, (byte) 224, (byte) 9, (byte) 146, - (byte) 180, (byte) 178, (byte) 22, (byte) 76, (byte) 82, - (byte) 229, (byte) 16, (byte) 150, (byte) 127, (byte) 13, - (byte) 122, (byte) 218, (byte) 159, (byte) 195, (byte) 232, - (byte) 168, (byte) 206, (byte) 105, (byte) 82, (byte) 37, - (byte) 252, (byte) 186, (byte) 223, (byte) 222, (byte) 7, - (byte) 106, (byte) 87, (byte) 218, (byte) 89, (byte) 22, - (byte) 252, (byte) 7, (byte) 177, (byte) 52, (byte) 180, (byte) 9, - (byte) 16, (byte) 29, (byte) 57, (byte) 192, (byte) 209, - (byte) 225, (byte) 155, (byte) 16, (byte) 219, (byte) 38, - (byte) 90, (byte) 174, (byte) 152, (byte) 140, (byte) 252, - (byte) 114, (byte) 133, (byte) 106, (byte) 24, (byte) 107, - (byte) 227, (byte) 80, (byte) 166, (byte) 63, (byte) 47, (byte) 16, - (byte) 15, (byte) 89, (byte) 242, (byte) 19, (byte) 87, (byte) 193, - (byte) 250, (byte) 222, (byte) 223, (byte) 183, (byte) 61, - (byte) 91, (byte) 17, (byte) 92, (byte) 35, (byte) 142, (byte) 44, - (byte) 153, (byte) 135, (byte) 86, (byte) 97, (byte) 70, - (byte) 205, (byte) 38, (byte) 192, (byte) 18, (byte) 244, - (byte) 61, (byte) 46, (byte) 21, (byte) 145, (byte) 99, (byte) 72, - (byte) 142, (byte) 37, (byte) 19, (byte) 219, (byte) 167, - (byte) 62, (byte) 71, (byte) 197, (byte) 86, (byte) 152, - (byte) 139, (byte) 122, (byte) 231, (byte) 122, (byte) 206, - (byte) 42, (byte) 142, (byte) 164, (byte) 237, (byte) 19, - (byte) 60, (byte) 95, (byte) 239, (byte) 191, (byte) 64, - (byte) 188, (byte) 94, (byte) 154, (byte) 199, (byte) 252, - (byte) 62, (byte) 26, (byte) 181, (byte) 194, (byte) 141, - (byte) 13, (byte) 1, (byte) 112, (byte) 161, (byte) 195, - (byte) 149, (byte) 116, (byte) 57, (byte) 118, (byte) 114, - (byte) 248, (byte) 235, (byte) 54, (byte) 229, (byte) 48, - (byte) 53, (byte) 30, (byte) 145, (byte) 199, (byte) 207, - (byte) 49, (byte) 175, (byte) 44, (byte) 172, (byte) 120, - (byte) 254, (byte) 181, (byte) 100, (byte) 113, (byte) 191, - (byte) 64, (byte) 131, (byte) 125, (byte) 80, (byte) 180, - (byte) 229, (byte) 109, (byte) 97, (byte) 8, (byte) 166, - (byte) 155, (byte) 72, (byte) 252, (byte) 84, (byte) 62, (byte) 97, - (byte) 80, (byte) 26, (byte) 17, (byte) 143, (byte) 96, (byte) 16, - (byte) 204, (byte) 86, (byte) 61, (byte) 226, (byte) 149 }; - - - public static KeyStore getKeyStore() - { - KeyStore ks = null; - try{ - ks = KeyStore.getInstance("JKS"); - ks.load(asInputStream(), getKeyStorePassword()); - }catch(Exception ex){ - throw new RuntimeException("Failed to load SSL key store.", ex); - } - return ks; - } - - public static InputStream asInputStream() { - return new ByteArrayInputStream(CERT_BYTES); - } - - public static char[] getCertificatePassword() { - return "inc0rrect".toCharArray(); - } - - public static char[] getKeyStorePassword() { - return "mu$tch8ng3".toCharArray(); - } - - public static String getCertificatePasswordString() { - return "inc0rrect"; - } - - public static String getKeyStorePasswordString() { - return "mu$tch8ng3"; - } - - private SecureSocketKeyStore() { - - } - -} diff --git a/src/main/java/com/myself/nettychat/common/ssl/SecureSocketSslContextFactory.java b/src/main/java/com/myself/nettychat/common/ssl/SecureSocketSslContextFactory.java deleted file mode 100644 index d4a0bf7..0000000 --- a/src/main/java/com/myself/nettychat/common/ssl/SecureSocketSslContextFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.myself.nettychat.common.ssl; - -import io.netty.util.internal.SystemPropertyUtil; - -import javax.net.ssl.*; -import java.security.KeyStore; -import java.security.SecureRandom; - -/** - * Creates a bogus {@link SSLContext}. A client-side context created by this - * factory accepts any certificate even if it is invalid. A server-side context - * created by this factory sends a bogus certificate defined in {@link }. - *

- * You will have to create your context differently in a real world application. - * - *

Client Certificate Authentication

- * - * To enable client certificate authentication: - *
    - *
  • Enable client authentication on the server side by calling - * {@link SSLEngine#setNeedClientAuth(boolean)} before creating - * {@link }.
  • - *
  • When initializing an {@link SSLContext} on the client side, - * specify the {@link KeyManager} that contains the client certificate as - * the first argument of {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)}.
  • - *
  • When initializing an {@link SSLContext} on the server side, - * specify the proper {@link TrustManager} as the second argument of - * {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)} - * to validate the client certificate.
  • - *
- */ -public final class SecureSocketSslContextFactory { - - private static final String PROTOCOL = "TLS"; - private static final SSLContext SERVER_CONTEXT; - private static final SSLContext CLIENT_CONTEXT; - - static { - String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm"); - if (algorithm == null) { - algorithm = "SunX509"; - } - - SSLContext serverContext; - SSLContext clientContext; - try { - // - //SecureSocketSslContextFactory.class.getResourceAsStream("/securesocket.jks") - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(SecureSocketKeyStore.asInputStream(), - SecureSocketKeyStore.getKeyStorePassword()); - - // Set up key manager factory to use our key store - KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); - kmf.init(ks, SecureSocketKeyStore.getCertificatePassword()); - - // Initialize the SSLContext to work with our key managers. - serverContext = SSLContext.getInstance(PROTOCOL); - serverContext.init(kmf.getKeyManagers(), null, null); - } catch (Exception e) { - throw new Error( - "Failed to initialize the server-side SSLContext", e); - } - - try { - clientContext = SSLContext.getInstance(PROTOCOL); - clientContext.init(null, SecureSokcetTrustManagerFactory.getTrustManagers(), null); - } catch (Exception e) { - throw new Error( - "Failed to initialize the client-side SSLContext", e); - } - - SERVER_CONTEXT = serverContext; - CLIENT_CONTEXT = clientContext; - } - - public static SSLContext getServerContext() { - return SERVER_CONTEXT; - } - - public static SSLContext getClientContext() { - return CLIENT_CONTEXT; - } - - private SecureSocketSslContextFactory() { - // Unused - } - -} diff --git a/src/main/java/com/myself/nettychat/common/ssl/SecureSokcetTrustManagerFactory.java b/src/main/java/com/myself/nettychat/common/ssl/SecureSokcetTrustManagerFactory.java deleted file mode 100644 index fdc57a1..0000000 --- a/src/main/java/com/myself/nettychat/common/ssl/SecureSokcetTrustManagerFactory.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.myself.nettychat.common.ssl; - -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactorySpi; -import javax.net.ssl.X509TrustManager; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.X509Certificate; - -/** - * Bogus {@link TrustManagerFactorySpi} which accepts any certificate - * even if it is invalid. - */ -public class SecureSokcetTrustManagerFactory extends TrustManagerFactorySpi { - - private static final TrustManager DUMMY_TRUST_MANAGER = new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) { - // Always trust - it is an example. - // You should do something in the real world. - // You will reach here only if you enabled client certificate auth, - // as described in SecureChatSslContextFactory. - System.err.println( - "UNKNOWN CLIENT CERTIFICATE: " + chain[0].getSubjectDN()); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) { - // Always trust - it is an example. - // You should do something in the real world. - System.err.println( - "UNKNOWN SERVER CERTIFICATE: 222 " + chain[0].getSubjectDN()); - } - }; - - public static TrustManager[] getTrustManagers() { - return new TrustManager[] { DUMMY_TRUST_MANAGER }; - } - - @Override - protected TrustManager[] engineGetTrustManagers() { - return getTrustManagers(); - } - - @Override - protected void engineInit(KeyStore keystore) throws KeyStoreException { - // Unused - } - - @Override - protected void engineInit(ManagerFactoryParameters managerFactoryParameters) - throws InvalidAlgorithmParameterException { - // Unused - } - -} diff --git a/src/main/java/com/myself/nettychat/common/ssl/StreamReader.java b/src/main/java/com/myself/nettychat/common/ssl/StreamReader.java deleted file mode 100644 index 25cf5b7..0000000 --- a/src/main/java/com/myself/nettychat/common/ssl/StreamReader.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.myself.nettychat.common.ssl; - -import java.io.InputStream; - -public class StreamReader { - - public String toByteArray(InputStream fin) - { - int i = -1; - StringBuilder buf = new StringBuilder(); - try{ - while((i=fin.read())!=-1){ - if(buf.length()>0) buf.append(","); - buf.append("(byte)"); - buf.append(i); - } - - }catch(Throwable e){ - ; - } - - return buf.toString(); - } - -} diff --git a/src/main/java/com/myself/nettychat/common/ssl/X509CertTool.java b/src/main/java/com/myself/nettychat/common/ssl/X509CertTool.java deleted file mode 100644 index be36d26..0000000 --- a/src/main/java/com/myself/nettychat/common/ssl/X509CertTool.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.myself.nettychat.common.ssl; - - - - -import sun.security.x509.*; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Date; - - -/** - * This class would require rt.jar in the class path in order to - * generated it alternative is using keytool. - */ -public class X509CertTool { - - /** - * Create a self-signed X.509 Certificate - * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" - * @param pair the KeyPair - * @param days how many days from now the Certificate is valid for - * @param algorithm the signing algorithm, eg "SHA1withRSA" - */ - @SuppressWarnings("restriction") - X509Certificate generateCertificate(String dn, KeyPair pair, int days, - String algorithm) throws GeneralSecurityException, IOException { - PrivateKey privkey = pair.getPrivate(); - X509CertInfo info = new X509CertInfo(); - Date from = new Date(); - Date to = new Date(from.getTime() + days * 86400000l); - CertificateValidity interval = new CertificateValidity(from, to); - BigInteger sn = new BigInteger(64, new SecureRandom()); - X500Name owner = new X500Name(dn); - - info.set(X509CertInfo.VALIDITY, interval); - info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); - info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); - info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); - info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); - info.set(X509CertInfo.VERSION, new CertificateVersion( - CertificateVersion.V3)); - AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); - info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); - - // Sign the cert to identify the algorithm that's used. - X509CertImpl cert = new X509CertImpl(info); - cert.sign(privkey, algorithm); - - // Update the algorith, and resign. - algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG); - info.set(CertificateAlgorithmId.NAME + "." - + CertificateAlgorithmId.ALGORITHM, algo); - cert = new X509CertImpl(info); - cert.sign(privkey, algorithm); - return cert; - } - - public static void main(String[] args) { - - } - -} diff --git a/src/main/java/com/myself/nettychat/common/zookeeper/ZkStateListener.java b/src/main/java/com/myself/nettychat/common/zookeeper/ZkStateListener.java deleted file mode 100644 index b2658fa..0000000 --- a/src/main/java/com/myself/nettychat/common/zookeeper/ZkStateListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.myself.nettychat.common.zookeeper; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.state.ConnectionState; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc zookeeper 监听 - **/ -public interface ZkStateListener { - - default void connectedEvent(CuratorFramework curator, ConnectionState state) { - } - - default void ReconnectedEvent(CuratorFramework curator, ConnectionState state) { - } - - default void lostEvent(CuratorFramework curator, ConnectionState state) { - } - -} diff --git a/src/main/java/com/myself/nettychat/common/zookeeper/ZkUtils.java b/src/main/java/com/myself/nettychat/common/zookeeper/ZkUtils.java deleted file mode 100644 index 1cc853b..0000000 --- a/src/main/java/com/myself/nettychat/common/zookeeper/ZkUtils.java +++ /dev/null @@ -1,366 +0,0 @@ -package com.myself.nettychat.common.zookeeper; - -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -import com.google.common.base.Charsets; -import com.google.common.base.Objects; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.GetDataBuilder; -import org.apache.curator.framework.recipes.cache.NodeCache; -import org.apache.curator.framework.recipes.cache.PathChildrenCache; -import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; -import org.apache.curator.framework.recipes.cache.TreeCache; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.retry.RetryNTimes; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.data.Stat; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Slf4j -@Data -@NoArgsConstructor -public class ZkUtils { - - private CuratorFramework zkClient = null; - - ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); - - List pathChildrenCaches = new CopyOnWriteArrayList<>(); - - List nodeCaches = new CopyOnWriteArrayList<>(); - - List treeCaches = new CopyOnWriteArrayList<>(); - - - /** - * 初始化zk链接 - * - * @param zookeeperServer - * @param connectionTimeout - * @param sessionTimeout - * @param maxRetries - * @param retriesSleepTime - * @param namespace - * @param listener - */ - public void init(String zookeeperServer, - int connectionTimeout, - int sessionTimeout, - int maxRetries, int retriesSleepTime, - String namespace, - ZkStateListener listener) { - if (zkClient == null) { - zkClient = CuratorFrameworkFactory.builder() - .connectString(zookeeperServer) - .connectionTimeoutMs(connectionTimeout) - .sessionTimeoutMs(sessionTimeout) - .namespace(namespace) - .retryPolicy(new RetryNTimes(maxRetries, retriesSleepTime)) - .build(); - } - zkClient.getConnectionStateListenable().addListener((curatorFramework, connectionState) -> { - pathChildrenCaches.clear(); - nodeCaches.clear(); - treeCaches.clear(); - if (connectionState == ConnectionState.CONNECTED) { - listener.connectedEvent(curatorFramework, connectionState); - } else if (connectionState == ConnectionState.RECONNECTED) { - listener.ReconnectedEvent(curatorFramework, connectionState); - } else if (connectionState == ConnectionState.LOST) { - listener.lostEvent(curatorFramework, connectionState); - } - }); - zkClient.start(); - } - /** - * 销毁所有 - */ - public void destory() { - pathChildrenCaches.stream().forEach(cache -> CloseableUtils.closeQuietly(cache)); - pathChildrenCaches.clear(); - pathChildrenCaches = null; - nodeCaches.stream().forEach(cache -> CloseableUtils.closeQuietly(cache)); - nodeCaches.clear(); - nodeCaches = null; - treeCaches.stream().forEach(cache -> CloseableUtils.closeQuietly(cache)); - treeCaches.clear(); - treeCaches = null; - if (zkClient != null) { - CloseableUtils.closeQuietly(zkClient); - } - } - - - /** - * 创建节点 - * - * @param path - * @param data - * @param mode - * @return - */ - public boolean createNode(String path, String data, CreateMode mode) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return Boolean.FALSE; - } - try { - Stat stat = exists(path); - if (stat == null) { - mode = mode == null ? CreateMode.PERSISTENT : mode; - String opResult; - if (ObjectUtils.allNotNull(data)) { - opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data.getBytes(Charsets.UTF_8)); - } else { - opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path); - } - return Objects.equal(opResult, path); - } - return Boolean.TRUE; - } catch (Exception e) { - log.error("create node fail! path: {}, error: {}", path, e); - } - return Boolean.FALSE; - } - - - /** - * 删除节点 递归删除子节点 - * - * @param path - * @param version - * @return - */ - public boolean deleteNode(String path, Integer version) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return Boolean.FALSE; - } - try { - Stat stat = exists(path); - if (stat != null) { - if (version == null) { - zkClient.delete().deletingChildrenIfNeeded().forPath(path); - } else { - zkClient.delete().deletingChildrenIfNeeded().withVersion(version).forPath(path); - } - } - return Boolean.TRUE; - } catch (Exception e) { - log.error("delete node fail! path: {}, error: {}", path, e); - } - return Boolean.FALSE; - } - - /** - * 删除节点 - * - * @param path - * @return - */ - public boolean deleteNode(String path) { - return deleteNode(path, null); - } - - /** - * 获取指定节点的值 - * - * @param path - * @return - */ - public byte[] getNodeData(String path) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return null; - } - try { - Stat stat = exists(path); - if (stat != null) { - return zkClient.getData().forPath(path); - } - } catch (Exception e) { - log.error("get node data fail! path: {}, error: {}", path, e); - } - return null; - } - - /** - * 获取指定节点的值 - * - * @param path - * @return - */ - public String getNodeDataStr(String path) { - byte[] val = getNodeData(path); - return val == null ? null : new String(val, Charsets.UTF_8); - } - - /** - * 检查节点是否存在 - * - * @param path - * @return - */ - public Stat exists(String path) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return null; - } - try { - return zkClient.checkExists().forPath(path); - } catch (Exception e) { - log.error("check node exists fail! path: {}, error: {}", path, e); - } - return null; - } - - /** - * 检查节点是否存在 - * - * @param path - * @return - */ - public boolean checkExists(String path) { - return exists(path) == null ? Boolean.FALSE : Boolean.TRUE; - } - - /** - * 设置节点数据 - * - * @param path - * @param data - * @return - */ - public boolean setNodeData(String path, String data) { - return setNodeData(path, data.getBytes(Charsets.UTF_8), null); - } - - /** - * 设置节点数据 - * - * @param path - * @param data - * @param version - * @return - */ - public boolean setNodeData(String path, byte[] data, Integer version) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return Boolean.FALSE; - } - try { - Stat stat = exists(path); - if (stat != null) { - if (version == null) { - zkClient.setData().forPath(path, data); - } else { - zkClient.setData().withVersion(version).forPath(path, data); - } - return Boolean.TRUE; - } - } catch (Exception e) { - log.error("set node data fail! path: {}, error: {}", path, e); - } - return Boolean.FALSE; - } - - /** - * 设置子节点更改监听 - * - * @param path - * @throws Exception - */ - public boolean listenerPathChildrenCache(String path, BiConsumer biConsumer) { - - if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) { - return Boolean.FALSE; - } - try { - Stat stat = exists(path); - if (stat != null) { - PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true); - watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); - //该模式下 watcher在重连的时候会自动 rebuild - watcher.getListenable().addListener(biConsumer::accept, pool); - if (!pathChildrenCaches.contains(watcher)) { - pathChildrenCaches.add(watcher); - } -// else{ -// watcher.rebuild(); -// } - return Boolean.TRUE; - } - } catch (Exception e) { - log.error("listen path children cache fail! path:{} , error:{}", path, e); - } - return Boolean.FALSE; - } - - - /** - * 读取指定节点的子菜单的值 - * - * @param path - * @return - */ - public Map readTargetChildsData(String path) { - if (!ObjectUtils.allNotNull(zkClient, path)) { - return null; - } - Map map = null; - try { - Stat stat = exists(path); - if (stat != null) { - List childrens = zkClient.getChildren().forPath(path); - GetDataBuilder dataBuilder = zkClient.getData(); - if (childrens != null) { - map = childrens.stream().collect(Collectors.toMap(Function.identity(), (child) -> { - try { - return new String(dataBuilder.forPath(ZKPaths.makePath(path, child)), Charsets.UTF_8); - } catch (Exception e1) { - return null; - } - })); - } - } - } catch (Exception e) { - log.error("get target childs data fail!, path:{} , error:{}", path, e); - } - return map; - - } - - - public static void main(String[] a) throws Exception { - ZkUtils zkUtils = new ZkUtils(); - zkUtils.init("127.0.0.1:2181", 1000, 2000, 5, 1000, "test", new ZkStateListener() { - @Override - public void connectedEvent(CuratorFramework curator, ConnectionState state) { - - } - - @Override - public void ReconnectedEvent(CuratorFramework curator, ConnectionState state) { - - } - - @Override - public void lostEvent(CuratorFramework curator, ConnectionState state) { - - } - }); - zkUtils.getZkClient().create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/yy/uu/ii"); - - Thread.sleep(Long.MAX_VALUE); - } - -} diff --git a/src/main/java/com/myself/nettychat/common/zookeeper/testZk.java b/src/main/java/com/myself/nettychat/common/zookeeper/testZk.java deleted file mode 100644 index e51292b..0000000 --- a/src/main/java/com/myself/nettychat/common/zookeeper/testZk.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.myself.nettychat.common.zookeeper; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.ACLProvider; -import org.apache.curator.framework.api.CuratorEvent; -import org.apache.curator.framework.api.CuratorListener; -import org.apache.curator.framework.recipes.cache.*; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.retry.RetryNTimes; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooDefs; -import org.apache.zookeeper.data.ACL; -import org.apache.zookeeper.data.Id; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author MySelf - * @create 2018/9/22 - * @desc 测试 - **/ -public class testZk { - - /** - * 先测试玩玩 - * @描述:XXXXXXX - * @param args - * @return void - * @exception - * @createTime:2016年5月17日 - * @author: songqinghu - * @throws Exception - */ - public static void main(String[] args) throws Exception { - CuratorFramework client = clientTwo(); - //setListenterDateNode(); - //setListenterThreeOne(client); - // setListenterThreeTwo(client); - setListenterThreeThree(client); - // getDataNode(client, "/two"); - // setDataNode(client, "/two", "sss"); - - } - - /** - * - * @描述:创建一个zookeeper连接---连接方式一: 最简单的连接 - * @return void - * @exception - * @createTime:2016年5月17日 - * @author: songqinghu - */ - private static CuratorFramework clientOne(){ - //zk 地址 - String connectString = "10.125.2.44:2181"; - // 连接时间 和重试次数 - RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); - CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy); - client.start(); - return client; - } - - /** - * - * @描述:创建一个zookeeper连接---连接方式二:优选这个 - * @return void - * @exception - * @createTime:2016年5月17日 - * @author: songqinghu - */ - private static CuratorFramework clientTwo(){ - - //默认创建的根节点是没有做权限控制的--需要自己手动加权限???---- - ACLProvider aclProvider = new ACLProvider() { - private List acl ; - @Override - public List getDefaultAcl() { - if(acl ==null){ - ArrayList acl = ZooDefs.Ids.CREATOR_ALL_ACL; - acl.clear(); - acl.add(new ACL(ZooDefs.Perms.ALL, new Id("auth", "admin:admin") )); - this.acl = acl; - } - return acl; - } - @Override - public List getAclForPath(String path) { - return acl; - } - }; - String scheme = "digest"; - byte[] auth = "admin:admin".getBytes(); - int connectionTimeoutMs = 5000; - String connectString = "127.0.0.1:2181"; - String namespace = "testnamespace"; - CuratorFramework client = CuratorFrameworkFactory.builder().aclProvider(aclProvider). - authorization(scheme, auth). - connectionTimeoutMs(connectionTimeoutMs). - connectString(connectString). - namespace(namespace). - retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)).build(); - client.start(); - return client; - } - - - /** - * - * @描述:第一种监听器的添加方式: 对指定的节点进行添加操作 - * 仅仅能监控指定的本节点的数据修改,删除 操作 并且只能监听一次 --->不好 - * @return void - * @exception - * @createTime:2016年5月18日 - * @author: songqinghu - * @throws Exception - */ - private static void setListenterOne(CuratorFramework client) throws Exception{ - // 注册观察者,当节点变动时触发 - byte[] data = client.getData().usingWatcher(new Watcher() { - @Override - public void process(WatchedEvent event) { - System.out.println("获取 two 节点 监听器 : " + event); - } - }).forPath("/two"); - System.out.println("two 节点数据: "+ new String(data)); - } - /** - * - * @描述:第二种监听器的添加方式: - * 也是一次性的监听操作,使用后就无法在继续监听了 - * @return void - * @exception - * @createTime:2016年5月18日 - * @author: songqinghu - * @throws Exception - */ - private static void setListenterTwo(CuratorFramework client) throws Exception{ - - ExecutorService pool = Executors.newCachedThreadPool(); - - CuratorListener listener = new CuratorListener() { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { - System.out.println("监听器 : "+ event.toString()); - } - }; - client.getCuratorListenable().addListener(listener,pool); - client.getData().inBackground().forPath("/two"); - client.getData().inBackground().forPath("/two"); - client.getData().inBackground().forPath("/two"); - client.getData().inBackground().forPath("/two"); - Thread.sleep(Long.MAX_VALUE ); - } - /** - * - * @描述:第三种监听器的添加方式: Cache 的三种实现 实践 - * Path Cache:监视一个路径下1)孩子结点的创建、2)删除,3)以及结点数据的更新。 - * 产生的事件会传递给注册的PathChildrenCacheListener。 - * Node Cache:监视一个结点的创建、更新、删除,并将结点的数据缓存在本地。 - * Tree Cache:Path Cache和Node Cache的“合体”,监视路径下的创建、更新、删除事件,并缓存路径下所有孩子结点的数据。 - * @return void - * @exception - * @createTime:2016年5月18日 - * @author: songqinghu - * @throws Exception - */ - //1.path Cache 连接 路径 是否获取数据 - //能监听所有的字节点 且是无限监听的模式 但是 指定目录下节点的子节点不再监听 - private static void setListenterThreeOne(CuratorFramework client) throws Exception{ - ExecutorService pool = Executors.newCachedThreadPool(); - PathChildrenCache childrenCache = new PathChildrenCache(client, "/test", true); - PathChildrenCacheListener childrenCacheListener = new PathChildrenCacheListener() { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { - System.out.println("开始进行事件分析:-----"); - ChildData data = event.getData(); - switch (event.getType()) { - case CHILD_ADDED: - System.out.println("CHILD_ADDED : "+ data.getPath() +" 数据:"+ data.getData()); - break; - case CHILD_REMOVED: - System.out.println("CHILD_REMOVED : "+ data.getPath() +" 数据:"+ data.getData()); - break; - case CHILD_UPDATED: - System.out.println("CHILD_UPDATED : "+ data.getPath() +" 数据:"+ data.getData()); - break; - default: - break; - } - } - }; - childrenCache.getListenable().addListener(childrenCacheListener); - System.out.println("Register zk watcher successfully!"); - childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); - } - - //2.Node Cache 监控本节点的变化情况 连接 目录 是否压缩 - //监听本节点的变化 节点可以进行修改操作 删除节点后会再次创建(空节点) - private static void setListenterThreeTwo(CuratorFramework client) throws Exception{ - ExecutorService pool = Executors.newCachedThreadPool(); - //设置节点的cache - final NodeCache nodeCache = new NodeCache(client, "/test", false); - nodeCache.getListenable().addListener(new NodeCacheListener() { - @Override - public void nodeChanged() throws Exception { - System.out.println("the test node is change and result is :"); - System.out.println("path : "+nodeCache.getCurrentData().getPath()); - System.out.println("data : "+new String(nodeCache.getCurrentData().getData())); - System.out.println("stat : "+nodeCache.getCurrentData().getStat()); - } - }); - nodeCache.start(); - } - //3.Tree Cache - // 监控 指定节点和节点下的所有的节点的变化--无限监听 可以进行本节点的删除(不在创建) - private static void setListenterThreeThree(CuratorFramework client) throws Exception{ - ExecutorService pool = Executors.newCachedThreadPool(); - //设置节点的cache - TreeCache treeCache = new TreeCache(client, "/test"); - //设置监听器和处理过程 - treeCache.getListenable().addListener(new TreeCacheListener() { - @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { - ChildData data = event.getData(); - if(data !=null){ - switch (event.getType()) { - case NODE_ADDED: - System.out.println("NODE_ADDED : "+ data.getPath() +" 数据:"+ new String(data.getData())); - break; - case NODE_REMOVED: - System.out.println("NODE_REMOVED : "+ data.getPath() +" 数据:"+ new String(data.getData())); - break; - case NODE_UPDATED: - System.out.println("NODE_UPDATED : "+ data.getPath() +" 数据:"+ new String(data.getData())); - break; - - default: - break; - } - }else{ - System.out.println( "data is null : "+ event.getType()); - } - } - }); - //开始监听 - treeCache.start(); - - } - -} diff --git a/src/main/java/com/myself/nettychat/constont/ResultConstant.java b/src/main/java/com/myself/nettychat/constont/ResultConstant.java new file mode 100644 index 0000000..2edc421 --- /dev/null +++ b/src/main/java/com/myself/nettychat/constont/ResultConstant.java @@ -0,0 +1,16 @@ +package com.myself.nettychat.constont; + +/** + * Created by MySelf on 2018/11/2. + */ +public interface ResultConstant { + + Integer PARAMS_CODE = 555; + + String PARAMS_MSG = "【参数错误】"; + + Integer USER_NAME_REPART_CODE = 556; + + String USER_NAME_REPART_MSG = "【用户名存在】"; + +} diff --git a/src/main/java/com/myself/nettychat/controller/NcChangeController.java b/src/main/java/com/myself/nettychat/controller/NcChangeController.java deleted file mode 100644 index feb492b..0000000 --- a/src/main/java/com/myself/nettychat/controller/NcChangeController.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.myself.nettychat.controller; - -import com.myself.nettychat.constont.CookieConstant; -import com.myself.nettychat.constont.H5Constant; -import com.myself.nettychat.dataobject.User; -import com.myself.nettychat.service.UserService; -import com.myself.nettychat.store.TokenStore; -import com.myself.nettychat.common.utils.CookieUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import java.util.Map; - -/** - * @Author:UncleCatMySelf - * @Email:zhupeijie_java@126.com - * @QQ:1341933031 - * @Date:Created in 15:59 2018\9\5 0005 - */ -@Controller -@RequestMapping("/su") -public class NcChangeController { - - @Autowired - private UserService userService; - - /** - * 我的中心界面 - * @param map - * @return - */ - @GetMapping("/me") - public ModelAndView Me(Map map){ - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = attributes.getRequest(); - Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN); - if (cookie == null){ - map.put("msg","cookie中不存在token"); - return new ModelAndView(H5Constant.LOGIN_SUI,map); - } - Integer userId = (Integer) TokenStore.get(cookie.getValue()); - if (userId == null){ - map.put("msg","用户信息不存在"); - return new ModelAndView(H5Constant.LOGIN_SUI,map); - } - User user = userService.findOne(userId); - map.put("userName",user.getUserName()); - return new ModelAndView(H5Constant.ME,map); - } - - /** - * 发现 - * @param map - * @return - */ - @GetMapping("/find") - public ModelAndView find(Map map){ - return new ModelAndView(H5Constant.FIND); - } - - /** - * 聊天 - * @param map - * @return - */ - @GetMapping("/chat") - public ModelAndView chat(Map map){ - return new ModelAndView(H5Constant.CHAT); - } - - /** - * 主页 - * @param map - * @return - */ - @GetMapping("/home") - public ModelAndView home(Map map){ - return new ModelAndView(H5Constant.HOME); - } - -} diff --git a/src/main/java/com/myself/nettychat/controller/NcLoginController.java b/src/main/java/com/myself/nettychat/controller/NcLoginController.java index 2db26fb..a99fdb3 100644 --- a/src/main/java/com/myself/nettychat/controller/NcLoginController.java +++ b/src/main/java/com/myself/nettychat/controller/NcLoginController.java @@ -1,21 +1,22 @@ package com.myself.nettychat.controller; +import com.myself.nettychat.common.utils.ResultVOUtil; import com.myself.nettychat.constont.CookieConstant; import com.myself.nettychat.constont.H5Constant; +import com.myself.nettychat.constont.ResultConstant; import com.myself.nettychat.dataobject.User; import com.myself.nettychat.form.LoginForm; import com.myself.nettychat.repository.UserMsgRepository; import com.myself.nettychat.service.UserService; import com.myself.nettychat.store.TokenStore; import com.myself.nettychat.common.utils.CookieUtil; +import com.myself.nettychat.vo.ResultVo; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; @@ -25,121 +26,75 @@ import java.util.UUID; /** + * 用户账号模块 * @Author:UncleCatMySelf * @Email:zhupeijie_java@126.com * @QQ:1341933031 * @Date:Created in 16:01 2018\8\18 0018 */ -@Controller -@RequestMapping("/admin") +@Slf4j +@RestController +@RequestMapping("/user") public class NcLoginController { @Autowired private UserService userService; - @Autowired - private UserMsgRepository userMsgRepository; - - /** - * 登录页面 - * @return - */ -// @GetMapping("/login") -// public ModelAndView login(Map map){ -// return new ModelAndView(H5Constant.LOGIN); -// } - - - /** - * 登录页面SUI - * @return - */ - @GetMapping("/loginsui") - public ModelAndView loginSui(Map map){ - return new ModelAndView(H5Constant.LOGIN_SUI); - } - - /** - * 注册页面 - * @return - */ - @GetMapping("/regis") - public ModelAndView register(){ - return new ModelAndView(H5Constant.LOGIN_SUI); - } - - /** - * 执行注册 - * @param form - * @param bindingResult - * @param response - * @param map - * @return + * 【账号注册】-2018-11-2 + * @param username 用户名 + * @param password 密码 + * @return {@link ResultVo} */ - @PostMapping("/toRegister") - public ModelAndView toRegister(@Valid LoginForm form, BindingResult bindingResult , HttpServletResponse response, - Map map){ - if (bindingResult.hasErrors()){ - map.put("msg",bindingResult.getFieldError().getDefaultMessage()); - return new ModelAndView(H5Constant.LOGIN_SUI,map); + @PostMapping(value = "/to_register") + public ResultVo toRegister(@RequestParam("username") String username,@RequestParam("password") String password){ + //参数非空判断,如前端实现,可省略 + if (username.isEmpty() | password.isEmpty()){ + log.info("user-【参数为空】"); + return ResultVOUtil.error(ResultConstant.PARAMS_CODE,ResultConstant.PARAMS_MSG); } + //TODO 用户过多,需优化 List userList = userService.findAll(); for (User item:userList){ - if (item.getUserName().equals(form.getFUserName())){ - map.put("msg","用户名已存在,请重新填写唯一用户名"); - return new ModelAndView(H5Constant.LOGIN_SUI,map); + if (item.getUserName().equals(username)){ + log.info("user-【用户名已存在】-"+username); + return ResultVOUtil.error(ResultConstant.USER_NAME_REPART_CODE,ResultConstant.USER_NAME_REPART_MSG); } } User user = new User(); - BeanUtils.copyProperties(form,user); + user.setUserName(username); + user.setPassWord(password); userService.save(user); - map.put("userName",user.getUserName()); - map.put("passWord",user.getPassWord()); - return new ModelAndView(H5Constant.LOGIN_SUI,map); + log.info("user-【账号注册成功】-"+username); + return ResultVOUtil.success("【账号注册成功】"); } - /** - * 登录判断 - * @return - */ - @PostMapping("/toLogin") - public ModelAndView toLogin(@RequestParam(value = "page",defaultValue = "1") Integer page, - @RequestParam(value = "size",defaultValue = "10") Integer size, - @Valid LoginForm form, BindingResult bindingResult , HttpServletResponse response, - Map map){ - if (bindingResult.hasErrors()){ - map.put("msg",bindingResult.getFieldError().getDefaultMessage()); - return new ModelAndView(H5Constant.LOGIN_SUI,map); - } - try { - User user = userService.findByUserName(form.getFUserName()); - if (user.getPassWord().equals(form.getFPassWord())){ - //登录成功 - String token = UUID.randomUUID().toString(); - //将token信息添加到系统缓存中 - TokenStore.add(token,user.getId()); - //将Token信息添加到Cookie中 - CookieUtil.set(response, CookieConstant.TOKEN,token,CookieConstant.EXPIRE); -// Sort sort = new Sort(Sort.Direction.DESC,"id"); -// Pageable pageable = new PageRequest(page-1,size,sort); -// Page userMsgPage = userMsgRepository.findAll(pageable); -// //日期颠倒 -// List userMsgList = new ArrayList<>(); -// for (int i = 0,j = userMsgPage.getContent().size()-1; i < userMsgPage.getContent().size();i++,j--){ -// userMsgList.add(userMsgPage.getContent().get(j)); -// } -// map.put("userMsgList",userMsgList); -// map.put("userName",user.getUserName()); - return new ModelAndView(H5Constant.HOME); - }else{ - map.put("msg","密码错误"); - return new ModelAndView(H5Constant.LOGIN_SUI,map); - } - }catch (Exception e){ - map.put("msg","用户不存在"); - return new ModelAndView(H5Constant.LOGIN_SUI,map); + + @PostMapping(value = "/to_login") + public ResultVo toLogin(@RequestParam("username") String username,@RequestParam("password") String password){ + //参数非空判断,如前端实现,可省略 + if (username.isEmpty() | password.isEmpty()){ + return ResultVOUtil.error(ResultConstant.PARAMS_CODE,ResultConstant.PARAMS_MSG); } +// try { +// User user = userService.findByUserName(form.getFUserName()); +// if (user.getPassWord().equals(form.getFPassWord())){ +// //登录成功 +// String token = UUID.randomUUID().toString(); +// //将token信息添加到系统缓存中 +// TokenStore.add(token,user.getId()); +// //将Token信息添加到Cookie中 +// CookieUtil.set(response, CookieConstant.TOKEN,token,CookieConstant.EXPIRE); +// return new ModelAndView(H5Constant.HOME); +// }else{ +// map.put("msg","密码错误"); +// return new ModelAndView(H5Constant.LOGIN_SUI,map); +// } +// }catch (Exception e){ +// +// return new ModelAndView(H5Constant.LOGIN_SUI,map); +// } + return ResultVOUtil.success(); } } diff --git a/src/main/java/com/myself/nettychat/dataobject/User.java b/src/main/java/com/myself/nettychat/dataobject/User.java index d00bbad..3d63dc5 100644 --- a/src/main/java/com/myself/nettychat/dataobject/User.java +++ b/src/main/java/com/myself/nettychat/dataobject/User.java @@ -1,6 +1,8 @@ package com.myself.nettychat.dataobject; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.Entity; @@ -20,6 +22,8 @@ @Data @Entity @DynamicUpdate +@NoArgsConstructor +@AllArgsConstructor public class User implements Serializable { private static final long serialVersionUID = 8143981246513357880L; diff --git a/src/main/java/com/myself/nettychat/tcptest/CRC16myself.java b/src/main/java/com/myself/nettychat/tcptest/CRC16myself.java deleted file mode 100644 index 9f50137..0000000 --- a/src/main/java/com/myself/nettychat/tcptest/CRC16myself.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.myself.nettychat.tcptest; - -import java.math.BigInteger; - -/** - * 获取数据格式,请勿乱更改test的值或长度 - * @Author:UncleCatMySelf - * @Email:zhupeijie_java@126.com - * @QQ:1341933031 - * @Date:Created in 19:39 2018\9\20 0020 - */ -public class CRC16myself { - - public static void main(String[] args) { - String test = "F5690137563CC8syyyyyyyyyyyyyyyyynnnnnnn"; - System.out.println("原始内容字符串:" + test); - String crcString = getCRC(test.getBytes()); - System.out.println("str:" + crcString); - int crc = getCRCInt(test.getBytes()); - System.out.println("hex:" + crc); - CRC16myself myself = new CRC16myself(); - float crc16 = myself.parseHex2Float(crcString); - System.out.println("10进制浮点型:" + crc16); - String crc16String = myself.parseFloat2Hex(crc16); - System.out.println("十六进制浮点型:" + crc16String); - System.out.println("输出字符串:" + "gz" + test + crcString + "xr"); - } - - /** - * 计算CRC16校验码 - * - * @param bytes 字节数组 - * @return {@link String} 校验码 - * @since 1.0 - */ - public static String getCRC(byte[] bytes) { - int CRC = 0x0000ffff; - int POLYNOMIAL = 0x0000a001; - int i, j; - for (i = 0; i < bytes.length; i++) { - CRC ^= ((int) bytes[i] & 0x000000ff); - for (j = 0; j < 8; j++) { - if ((CRC & 0x00000001) != 0) { - CRC >>= 1; - CRC ^= POLYNOMIAL; - } else { - CRC >>= 1; - } - } - } - return Integer.toHexString(CRC); - } - - - /** - * 计算CRC16校验码 - * - * @param bytes 字节数组 - * @return {@link String} 校验码 - * @since 1.0 - */ - public static Integer getCRCInt(byte[] bytes) { - int CRC = 0x0000ffff; - int POLYNOMIAL = 0x0000a001; - int i, j; - for (i = 0; i < bytes.length; i++) { - CRC ^= ((int) bytes[i] & 0x000000ff); - for (j = 0; j < 8; j++) { - if ((CRC & 0x00000001) != 0) { - CRC >>= 1; - CRC ^= POLYNOMIAL; - } else { - CRC >>= 1; - } - } - } - return CRC; - } - - /** - * 将16进制单精度浮点型转换为10进制浮点型 - * - * @return float - * @since 1.0 - */ - private float parseHex2Float(String hexStr) { - BigInteger bigInteger = new BigInteger(hexStr, 16); - return Float.intBitsToFloat(bigInteger.intValue()); - } - - /** - * 将十进制浮点型转换为十六进制浮点型 - * - * @return String - * @since 1.0 - */ - private String parseFloat2Hex(float data) { - return Integer.toHexString(Float.floatToIntBits(data)); - } - -} diff --git a/src/main/java/com/myself/nettychat/tcptest/TCPTestClient.java b/src/main/java/com/myself/nettychat/tcptest/TCPTestClient.java deleted file mode 100644 index 083983a..0000000 --- a/src/main/java/com/myself/nettychat/tcptest/TCPTestClient.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.myself.nettychat.tcptest; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.net.Socket; -import java.net.SocketTimeoutException; - -/** - * 先去同包下CRC16myself下执行获取数据,数据格式有规定 - * TCP端测试模拟,建议放置在另一个项目 - * @Author:UncleCatMySelf - * @Email:zhupeijie_java@126.com - * @QQ:1341933031 - * @Date:Created in 19:40 2018\9\20 0020 - */ -public class TCPTestClient { - - public static void main(String[] args) throws IOException { - //10万测试 - for (int i = 0;i<100000;i++){ - new Thread(new Runnable() { - @Override - public void run() { - try { - runtest(); - }catch (Exception e){ - e.printStackTrace(); - } - } - }).start(); - sleep(100); - } - } - - private static void runtest() throws IOException{ - //客户端请求与本机在18866端口建立TCP连接 - Socket client = new Socket("127.0.0.1", 8092); - client.setSoTimeout(10000); - //获取键盘输入 - BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); - //获取Socket的输出流,用来发送数据到服务端 - PrintStream out = new PrintStream(client.getOutputStream()); - //获取Socket的输入流,用来接收从服务端发送过来的数据 - BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream())); - boolean flag = true; - int i = 1; - while(flag){ - //if (i == 1){ - //帧头+ID+数据类型+24把锁状态+crc校验+帧尾 - String str = "test"; - //发送数据到服务端 - out.println(str); - if("bye".equals(str)){ - flag = false; - }else{ - try{ - //从服务器端接收数据有个时间限制(系统自设,也可以自己设置),超过了这个时间,便会抛出该异常 - String echo = buf.readLine(); - System.out.println(echo); - }catch(SocketTimeoutException e){ - System.out.println("Time out, No response"); - } - } - sleep(5000); - } - input.close(); - if(client != null){ - //如果构造函数建立起了连接,则关闭套接字,如果没有建立起连接,自然不用关闭 - client.close(); //只关闭socket,其关联的输入输出流也会被关闭 - } - } - - private static void sleep(Integer time){ - try { - Thread.sleep(time); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 77aaf54..5a1dd6b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,14 +2,10 @@ spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: root - password: root - url: jdbc:mysql://localhost:3306/nettychat?characterEncoding=utf-8&useSSL=false + password: 123456 + url: jdbc:mysql://192.168.1.207:3306/nettychat?characterEncoding=utf-8&useSSL=false jpa: show-sql: true -# database: oracle -# properties: -# hibernate: -# dialect: org.hibernate.dialect.Oracle12cDialect server: servlet: context-path: /susu diff --git a/src/main/resources/static/css/allchat.css b/src/main/resources/static/css/allchat.css deleted file mode 100644 index b35a89f..0000000 --- a/src/main/resources/static/css/allchat.css +++ /dev/null @@ -1,59 +0,0 @@ -.history{ - width: 90%; -} - -.his{ - margin-right: auto; - border-left: 20px; - padding-left: 20px; -} - -.chat { - width: 100%; - position: absolute; - box-sizing: border-box; - padding: 10px 4px; - padding-top: 20px; - bottom: 0; -} - -.msgCente{ - text-align: center; - margin-bottom: 100px; -} - -.chatimg{ - height: 90px; - width: 90px; -} - -.msgRight { - text-align: right; -} - -.msgLeft { - text-align: left; -} - -.msgLeft, -.msgRight { - margin-bottom: 26px; -} - -.msgLeft>span, -.msgRight>span { - padding: 10px; - font-size: 16px; - line-height: 20px; - border-radius: 10px; -} - -.msgLeft>span { - background-color: #d8f1f9; - box-shadow: inset -2px -3px 8px 1px #75ddff; -} - -.msgRight>span { - background-color: #FFF; - box-shadow: inset -2px -3px 8px 1px #d8d8d8; -} \ No newline at end of file diff --git a/src/main/resources/static/css/chat.css b/src/main/resources/static/css/chat.css deleted file mode 100644 index 3a25d39..0000000 --- a/src/main/resources/static/css/chat.css +++ /dev/null @@ -1,43 +0,0 @@ -form { - width: 406px; - height: 650px; - border: 4px solid #98bcde; - border-radius: 10px; - margin: 0 auto; - background-color: #eceff9; - display: flex; - flex-wrap: wrap; - justify-content: space-around; -} - -h3 { - color: #92acdc; - text-align: center; - font-size: 26px; -} - -textarea { - resize: none; - font-size: 20px; - width: 401px; - height: 511px; -} - -.msg { - width: 324px; - height: 40px; - text-indent: 10px; - font-size: 20px; - outline: none; -} - -.btn { - width: 78px; - height: 46px; - background-color: #d8f1f9; - border-radius: 6px; - border: 1px solid #98bcde; - font-size: 18px; - color: #92acdc; - font-weight: bold; -} \ No newline at end of file diff --git a/src/main/resources/static/css/newChat.css b/src/main/resources/static/css/newChat.css deleted file mode 100644 index 77f1406..0000000 --- a/src/main/resources/static/css/newChat.css +++ /dev/null @@ -1,172 +0,0 @@ -.container { - width: 750px; - border: 4px solid #98bcde; - border-radius: 10px; - margin: 100px auto; - background-color: #fff; - /*display: flex; - justify-content: space-around;*/ - display: table; - clear: both; - overflow: hidden; -} - -.left_content { - width: 160px; - height: 600px; - background-color: #d8f1f9; - float: left; - text-align: center; -} - -.content { - width: 590px; - height: 600px; - background-color: #FFF; - float: right; -} - -.content_top { - width: 100%; - height: 80px; - background-color: #6fdcff; - position: relative; -} - -.content_top .tips { - text-align: center; - font-size: 16px; - line-height: 30px; - color: #000000; -} - -.content_bodyer { - width: 100%; - height: 410px; - background: #f4f4f4; - overflow: hidden; - position: relative; -} - -.chat { - width: 100%; - position: absolute; - box-sizing: border-box; - padding: 10px 4px; - padding-top: 20px; - bottom: 0; -} - -form { - width: 100%; - height: 110px; - position: relative; -} - -textarea { - resize: none; - font-size: 20px; - width: 100%; - height: 511px; -} - -.msg { - width: 486px; - border: none; - height: 74px; - box-sizing: border-box; - padding: 4px 10px; - font-size: 20px; - outline: none; -} - -.btn { - width: 78px; - height: 30px; - background-color: #d8f1f9; - border-radius: 6px; - border: 1px solid #98bcde; - font-size: 16px; - color: #92acdc; - font-weight: bold; - position: absolute; - bottom: 4px; - right: 4px; -} - -.openHistory { - font-size: 16px; - color: #000; - z-index: 10; - position: absolute; - bottom: 5px; - right: 5px; - cursor: pointer; -} - -.history { - width: 250px; - height: 410px; - background-color: rgba(0, 0, 0, 0.5); - color: #FFF; - font-size: 16px; - position: absolute; - top: 0; - right: 0; - display: none; - z-index: 10; -} - -.scrollbar { - width: 12px; - height: 100%; - background: black; - position: absolute; - right: 0; - top: 0; - opacity: 0.5; - overflow: hidden; - display: none; - z-index: 10; -} - -.scrollbar .thumb { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 40px; - background: #6d6a6a; - cursor: pointer; -} - -.msgRight { - text-align: right; -} - -.msgLeft { - text-align: left; -} - -.msgLeft, -.msgRight { - margin-bottom: 26px; -} - -.msgLeft>span, -.msgRight>span { - padding: 10px; - font-size: 16px; - line-height: 20px; - border-radius: 10px; -} - -.msgLeft>span { - background-color: #d8f1f9; - box-shadow: inset -2px -3px 8px 1px #75ddff; -} - -.msgRight>span { - background-color: #FFF; - box-shadow: inset -2px -3px 8px 1px #d8d8d8; -} \ No newline at end of file diff --git a/src/main/resources/static/css/registered.css b/src/main/resources/static/css/registered.css deleted file mode 100644 index 206cf22..0000000 --- a/src/main/resources/static/css/registered.css +++ /dev/null @@ -1,160 +0,0 @@ -* { - margin: 0; - padding: 0; -} - -.bodyer .panel { - width: 362px; - height: 320px; - border-radius: 6px; - margin: 90px auto; - background: #FFF; - position: relative; - overflow: hidden; -} - -.logo { - width: 100px; - height: 100px; - background: url("../image/logoSmall.png") no-repeat; - position: absolute; - top: 29px; - right: -8px; - transform: rotate(30deg); -} - -.panel_tit { - text-align: center; - line-height: 40px; - font-size: 24px; - padding-top: 20px; - color: #92acdc; -} - -.bodyer .panel .register { - padding-left: 45px; - float: left; - color: #999; - width: 268px; - position: relative; -} - -.bodyer .panel .register .register_top { - font-size: 14px; - margin: 30px 0 26px; -} - -.bodyer .panel .register .register_top span { - margin: 0 2px; -} - -.bodyer .panel .register .register_top a { - font-size: 14px; - text-decoration: none; -} - -.bodyer .panel .register .register_top a:first-child { - color: #303030; -} - -.bodyer .panel .register .register_top a:last-child { - color: #999; -} - -.bodyer .panel .register input { - font-size: 14px; - width: 268px; - height: 38px; - display: block; - box-sizing: border-box; - border: 1px solid #dfdfdf; - padding: 8px 0 8px 36px; -} - -.bodyer .panel .register .user_icon { - position: relative; - margin-bottom: 18px; -} - -.bodyer .panel .register .user_icon input:focus { - border: 1px solid #98bcde; - outline: #98bcde solid 1px; -} - -.bodyer .panel .register .user_icon i { - position: absolute; - display: block; - width: 30px; - height: 30px; - background: url("../image/nuandao.png") no-repeat -310px -390px; -} - -.bodyer .panel .register .pass_icon { - position: relative; - margin-bottom: 30px; -} - -.bodyer .panel .register .pass_icon input:focus { - border: 1px solid #98bcde; - outline: #98bcde solid 1px; -} - -.bodyer .panel .register .pass_icon i { - position: absolute; - display: block; - width: 30px; - height: 30px; - background: url("../image/nuandao.png") no-repeat -333px -434px; -} - -.bodyer .panel .register .pass_icon span { - position: absolute; - left: 0; - bottom: -20px; - color: #d9534f; - font-size: 13px; - display: none; -} - -.bodyer .panel .register input.btn1 { - margin: 0; - padding: 0; - display: block; - width: 100%; - height: 40px; - font-size: 16px; - line-height: 40px; - text-align: center; - text-decoration: none; - color: #FFF; - background: #98bcde; - margin-bottom: 20px; -} - -.bodyer .panel .register input.btn1:hover { - background: #5694ce; -} - -.tips { - width: 100px; - height: 30px; - text-align: center; - font-size: 14px; - line-height: 30px; - background-color: rgba(0, 0, 0, 0.5); - color: #FFF; - position: absolute; - top: 35%; - left: 40%; - display: none; -} - -.mask2 { - width: 100%; - height: 100%; - z-index: -100; - position: fixed; - top: 0; - left: 0; - background: rgba(0, 0, 0, 0.5); -} \ No newline at end of file diff --git a/src/main/resources/static/image/logoBig.jpg b/src/main/resources/static/image/logoBig.jpg deleted file mode 100644 index 0c62304..0000000 Binary files a/src/main/resources/static/image/logoBig.jpg and /dev/null differ diff --git a/src/main/resources/static/image/logoSmall.png b/src/main/resources/static/image/logoSmall.png deleted file mode 100644 index 08b5d51..0000000 Binary files a/src/main/resources/static/image/logoSmall.png and /dev/null differ diff --git a/src/main/resources/static/image/nuandao.png b/src/main/resources/static/image/nuandao.png deleted file mode 100644 index be015d1..0000000 Binary files a/src/main/resources/static/image/nuandao.png and /dev/null differ diff --git a/src/main/resources/static/js/chat.js b/src/main/resources/static/js/chat.js deleted file mode 100644 index 3380613..0000000 --- a/src/main/resources/static/js/chat.js +++ /dev/null @@ -1,51 +0,0 @@ -var socket; -if(!window.WebSocket) { - window.WebSocket = window.MozWebSocket; -} - -if(window.WebSocket) { - socket = new WebSocket("ws://localhost:8090/ws"); - socket.onmessage = function(event) { - var ta = document.getElementById('responseText'); - ta.value = ta.value + '\n' + event.data - }; - socket.onopen = function(event) { - var ta = document.getElementById('responseText'); - if(msg.length > 0){ - ta.value = "--- 连接开启! ---"+'\n'+msg; - }else{ - ta.value = "--- 连接开启! ---" - } - }; - socket.onclose = function(event) { - var ta = document.getElementById('responseText'); - ta.value = ta.value + "连接被关闭"; - }; -} else { - alert("你的浏览器不支持 WebSocket!"); -} - -function send(message) { - if(!window.WebSocket) { - return; - } - if(socket.readyState == WebSocket.OPEN) { - socket.send(message); - } else { - alert("连接没有开启."); - } -} - -window.onbeforeunload = function(event) { - event.returnValue = "刷新提醒"; -} - -; -document.onkeydown = function(e) { - var userName = document.getElementById('userName'); - if(e.keyCode == 13) { - var message = userName.value + '-' +document.getElementsByClassName('msg')[0].value; - send(message); - document.getElementsByClassName('msg')[0].value = ''; - } -} \ No newline at end of file diff --git a/src/main/resources/static/js/newChat.js b/src/main/resources/static/js/newChat.js deleted file mode 100644 index 1bc7e78..0000000 --- a/src/main/resources/static/js/newChat.js +++ /dev/null @@ -1,165 +0,0 @@ -var socket; -if(!window.WebSocket) { - window.WebSocket = window.MozWebSocket; -} - -var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; - -function generateMixed(n) { - var res = ""; - for(var i = 0; i < n ; i ++) { - var id = Math.ceil(Math.random()*35); - res += chars[id]; - } - return res; -} - -if(window.WebSocket) { - socket = new WebSocket("ws://localhost:8090/ws"); - socket.onmessage = function(event) { - var msg = event.data; - console.log(msg); - if(msg instanceof Blob){ - console.log("blobs"); - var idran = generateMixed(3); - var ta = "
"; - $('.chat').append(ta); - //var previewImg = document.querySelector('img'); - var previewImg = document.getElementById(idran); - - var reader = new FileReader(); - // 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片 - reader.addEventListener("load", function () { - previewImg.src = reader.result; - }, false); - // 调用reader.readAsDataURL()方法,把图片转成base64 - reader.readAsDataURL(msg); - } - if(msg.substring(0, 1) == '[') { - var ta = "
"+event.data+"
"; - $('.chat').append(ta); - } else { - var ta = "
"+event.data+"
"; - $('.chat').append(ta); - } - }; - socket.onopen = function(event) { - $('.tips').html('连接开启!'); - $('.tips').css('color', 'green'); - - var his = $('#TTHistory'); - - console.log(msg); - his.html(msg); - }; - socket.onclose = function(event) { - $('.tips').html('连接被关闭'); - $('.tips').css('color', 'red'); - }; -} else { - var ta = "
你的浏览器不支持 WebSocket!
"; - $('.content_bodyer').append(ta); -} - -function send(message) { - if(!window.WebSocket) { - return; - } - if(socket.readyState == WebSocket.OPEN) { - socket.send(message); - } else { - alert("连接没有开启."); - } -} - -window.onbeforeunload = function(event) { - event.returnValue = "刷新提醒"; -} - -; -// document.onkeydown = function(e) { -// -// var userName = $('#userName'); -// if(e.keyCode == 13) { -// $('.chat').css('bottom', 0); -// var message = userName.val() + '-' + $('.msg').val().trim(); -// send(message); -// $('.msg').val(''); -// } -// } - -function sendd() { - var userName = $('#userName'); - var message = userName.val() + '-' + $('.msg').val().trim(); - send(message); - sendFile(); - $('.msg').val(''); -} - -$('.openHistory').click(function() { - $('.history').fadeToggle(); -}); - -$('.content_bodyer').mouseenter(function() { - $('.scrollbar').fadeIn(); -}) - -$('.content_bodyer').mouseleave(function() { - $('.scrollbar').fadeOut(); -}) - -function sendFile(){ - var thum = $('#file')[0].files[0]; - if(!thum) return; - console.log(thum); - var reader = new FileReader(); - //以二进制形式读取文件 - reader.readAsArrayBuffer(thum); - //文件读取完毕后该函数响应 - reader.onload = function loaded(evt) { - console.log(evt); - var blob = evt.target.result; - //发送二进制表示的文件 - socket.send(blob); - console.log(blob); - - console.log("finnish"); - } -} - -var thumb = $('.thumb'); -var scrollBar = $('.scrollbar'); -var chat = $('.chat'); - -thumb.on('mousedown', function(e) { - chat.css('bottom', 'initial'); - thumb.isMouseDown = true; - return false; -}); - -thumb.on('selectstart', function() { - return false; -}); - -$(window).on('mouseup', function(e) { - thumb.isMouseDown = false; -}); - -$(window).on('mousemove', function(e) { - if (thumb.isMouseDown){ - var pos = e.clientY - scrollBar.parent().offset().top - thumb.height() / 2; - if (pos < 0 ){ - pos = 0; - } else if(pos > scrollBar.height() - thumb.height()){ - pos = scrollBar.height() - thumb.height(); - } - thumb.css("top", pos + "px"); - - // 计算thumb所在的位置占父亲的% - var percentage = thumb.offset().top / (scrollBar.height() - thumb.height()); - var top = (chat.height() - chat.parent().height()) * percentage; - chat.css("top", -top + "px"); - } -}) - - diff --git a/src/main/resources/static/js/registered.js b/src/main/resources/static/js/registered.js deleted file mode 100644 index ebd3ea0..0000000 --- a/src/main/resources/static/js/registered.js +++ /dev/null @@ -1,72 +0,0 @@ -var register = $('.register_top').children().first(); -var register2 = $('.register_top').children().last(); -register.click(function () { - $(register).css('color', ' #303030'); - register2.css('color', '#999'); - $('.btn1').val('登陆'); - $('form').attr("action", "/susu/admin/toLogin"); -}); -register2.click(function () { - $(register2).css('color', ' #303030'); - register.css('color', '#999'); - $('.btn1').val('注册'); - $('form').attr("action", "/susu/admin/toRegister"); -}); -$('.btn3').click(function () { - $('.more').slideToggle(0); -}); - -/** - * 用户名验证 - */ -var input1 = $('.user_icon').children('input'); -var userName = /^[\u4e00-\u9fa5_a-zA-Z]{2,5}$/; -input1.blur(function () { - var val = input1.val().trim(); - if (val.length == 0) { - $($('.Span').children()[0]).css('display', 'block'); - $($('.Span').children()[0]).siblings().css('display', 'none'); - } else if (userName.test(val)) { - $($('.Span').children('span')).css('display', 'none'); - } else { - $($('.Span').children()[1]).css('display', 'block'); - $($('.Span').children()[1]).siblings().css('display', 'none'); - } -}); - -/** - * 密码验证 - */ -var input2 = $('.pass_icon').children('input'); -// 关于密码的正则表达式(6-16位数字和字母的组合) -var Password = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/; -input2.blur(function () { - var val = input2.val().trim(); - if (val.length == 0) { - $($('.Span').children()[2]).css('display', 'block'); - $($('.Span').children()[2]).siblings().css('display', 'none'); - } else if (Password.test(val)) { - console.log(1); - $($('.Span').children('span')).css('display', 'none'); - } else { - $($('.Span').children()[3]).css('display', 'block'); - $($('.Span').children()[3]).siblings().css('display', 'none'); - } -}); - -//登录注册校验 -$('form').submit(function(e) { - var User = $('.user_icon').children('input'); - var Pass = $('.pass_icon').children('input'); - var md5_pwd= $('#md5_pwd'); - if (userName.test(User) && Password.test(Pass)) { - return true; - } -}) - -function MsgTo() { - $('.tips').fadeIn(10, function() { - $('.tips').fadeOut(1500); - }); -} - diff --git a/src/main/resources/templates/chat/allchat.ftl b/src/main/resources/templates/chat/allchat.ftl deleted file mode 100644 index 317cd89..0000000 --- a/src/main/resources/templates/chat/allchat.ftl +++ /dev/null @@ -1,49 +0,0 @@ - - -<#include "../common/header.ftl"> - - - -
-
- - - -

全体用户

-
- -
-
- -
-
- -
-
-
-
-
- -
- -
-
- <#--Image preview area...--> -
-
- - -<#include "../common/floor.ftl"> - - - \ No newline at end of file diff --git a/src/main/resources/templates/chat/chat.ftl b/src/main/resources/templates/chat/chat.ftl deleted file mode 100644 index f18b178..0000000 --- a/src/main/resources/templates/chat/chat.ftl +++ /dev/null @@ -1,33 +0,0 @@ - - -<#include "../common/header.ftl"> - - -<#include "../common/floor.ftl"> - - \ No newline at end of file diff --git a/src/main/resources/templates/common/floor.ftl b/src/main/resources/templates/common/floor.ftl deleted file mode 100644 index 9b8124e..0000000 --- a/src/main/resources/templates/common/floor.ftl +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/main/resources/templates/common/header.ftl b/src/main/resources/templates/common/header.ftl deleted file mode 100644 index d519ed4..0000000 --- a/src/main/resources/templates/common/header.ftl +++ /dev/null @@ -1,12 +0,0 @@ - - - - 酥酥 - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/find/find.ftl b/src/main/resources/templates/find/find.ftl deleted file mode 100644 index b0feb38..0000000 --- a/src/main/resources/templates/find/find.ftl +++ /dev/null @@ -1,41 +0,0 @@ - - -<#include "../common/header.ftl"> - -
-
-

酥酥

-
- -
-
-
    -
  • -
    -
    朋友圈
    -
    -
  • -
-
-
-
-<#include "../common/floor.ftl"> - - \ No newline at end of file diff --git a/src/main/resources/templates/h5.ftl b/src/main/resources/templates/h5.ftl deleted file mode 100644 index a650b30..0000000 --- a/src/main/resources/templates/h5.ftl +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - Su Su - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/home/home.ftl b/src/main/resources/templates/home/home.ftl deleted file mode 100644 index f76b3b4..0000000 --- a/src/main/resources/templates/home/home.ftl +++ /dev/null @@ -1,62 +0,0 @@ - - -<#include "../common/header.ftl"> - - -
-
-

酥酥

-
- -
- - - <#--
--> -
-
    -
  • -
    -
    全体用户
    -
    -
  • -
-
- <#-- - <#--
--> - <#--
--> - <#--
--> - <#--
--> -
-
-<#include "../common/floor.ftl"> - - - \ No newline at end of file diff --git a/src/main/resources/templates/login/login.ftl b/src/main/resources/templates/login/login.ftl deleted file mode 100644 index 17e5a2a..0000000 --- a/src/main/resources/templates/login/login.ftl +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - Su Su - - - - - - - -
-
- - - -
-
- -

“酥酥”聊天室

-
-
- 登录 - | - 注册 -
-
-
-
- - -
- 请填写用户名 - 2-5位中文字符和英文字符 - 请填写6-16位数字和字母的组合密码 - 密码格式有误 - <#--${msg!''}--> -
-
- - -
${msg!''}
- -
-
- - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/login/loginSui.ftl b/src/main/resources/templates/login/loginSui.ftl deleted file mode 100644 index 40a962c..0000000 --- a/src/main/resources/templates/login/loginSui.ftl +++ /dev/null @@ -1,124 +0,0 @@ - - -<#include "../common/header.ftl"> - -
-
- -
-

登录

-
- - - - -
-
-
    -
  • -
    -
    -
    -
    账号
    -
    - -
    -
    -
    -
  • -
  • -
    -
    -
    -
    密码
    -
    - -
    -
    -
    -
  • -
-
-
-
- - -
-
-
- -
- -
-
-

注册

-
-
-
- -
-
    - -
  • -
    -
    -
    -
    账号
    -
    - -
    -
    -
    -
  • -
  • -
    -
    -
    -
    密码
    -
    - -
    -
    -
    -
  • -
-
-
-
- - -
-
- -
-
-
- -
-<#include "../common/floor.ftl"> - - - \ No newline at end of file diff --git a/src/main/resources/templates/me/me.ftl b/src/main/resources/templates/me/me.ftl deleted file mode 100644 index 5997f0d..0000000 --- a/src/main/resources/templates/me/me.ftl +++ /dev/null @@ -1,78 +0,0 @@ - - -<#include "../common/header.ftl"> - -
-
-

酥酥

-
- -
-
-
    -
  • -
    -
    ${userName!''}
    -
    -
  • -
-
-
-
-
    -
  • -
    -
    收藏
    -
    -
  • -
-
-
-
    -
  • -
    -
    相册
    -
    -
  • -
-
-
-
    -
  • -
    -
    卡包
    -
    -
  • -
-
-
-
    -
  • -
    -
    表情
    -
    -
  • -
-
-
-
-<#include "../common/floor.ftl"> - - \ No newline at end of file