first commit

This commit is contained in:
2026-02-23 16:25:54 +08:00
commit 328786d9e1
78 changed files with 20840 additions and 0 deletions

33
hs-web3d-server/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

316
hs-web3d-server/mvnw vendored Normal file
View File

@@ -0,0 +1,316 @@
#!/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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven 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 /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
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 Mingw, 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)`"
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="`\\unset -f command; \\command -v 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
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
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
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

188
hs-web3d-server/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,188 @@
@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 https://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 Maven 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 keystroke 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 set title of command window
title %0
@REM enable echoing by 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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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%
cmd /C exit /B %ERROR_CODE%

90
hs-web3d-server/pom.xml Normal file
View File

@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.huashi</groupId>
<artifactId>hs-web3d-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hs-web3d-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>artemis-http-client</groupId>
<artifactId>hk</artifactId>
<version>1.1.3</version>
</dependency>
</dependencies>
<build>
<finalName>hs-web3d-server</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,13 @@
package com.huashi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HsWeb3dServerApplication {
public static void main(String[] args) {
SpringApplication.run(HsWeb3dServerApplication.class, args);
}
}

View File

@@ -0,0 +1,26 @@
package com.huashi.config;
import com.huashi.websocket.SocketServer;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 监听Spring容器启动完成完成后启动Netty服务器
* @author Gjing
**/
@Component
public class NettyStartListener implements ApplicationRunner {
@Resource
private SocketServer socketServer;
@Override
public void run(ApplicationArguments args) throws Exception {
this.socketServer.start();
}
}

View File

@@ -0,0 +1,45 @@
package com.huashi.dto;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class DataContent implements Serializable {
@JsonProperty("appId")
private String appId; // 应用id
@JsonProperty("sessionId")
private String sessionId; // sessionId
@JsonProperty("role")
private String role; // ue 或者 web
@JsonProperty("client_id")
private String clientId; // 客户端ID
@JsonProperty("action")
private String action; // 动作类型
@JsonProperty("data")
private String data; // 用户的聊天内容entity
@JsonProperty(value = "code",defaultValue = "1")
private String code; // 用户的聊天
/**
* 音视频类型
* 1--表示单人视频
* 11表示发起邀请邀请进入房间等候语音
* 14表示已经同意邀请进入房间了在janus中已注册邀请方可以正式向janus发videocall
* 4--表示群组视频邀请
* 41表示发起邀请此时视频发起者已经进入房间接收方收到后41后应该进入房间
* */
private String extand=""; // 扩展字段
}

View File

@@ -0,0 +1,19 @@
package com.huashi.enums;
public enum ConnectRoleEnum {
SERVER("server", "core服务端"),
UE("ue", "ue引擎端"),
WEB("web", "web端");
public final String type;
public final String content;
ConnectRoleEnum(String type, String content){
this.type = type;
this.content = content;
}
public String getType() {
return type;
}
}

View File

@@ -0,0 +1,27 @@
package com.huashi.enums;
/**
*
* @Description: 发送消息的动作 枚举
*/
public enum MsgActionEnum {
CONNECT("1", "第一次(或重连)初始化连接"),
CHAT("2", "发送给单个客户端普通消息"),
CHATToCurrentUserGroup("3", "发送给当前用户所在的组"),
CHATUSERLISTINFO("100", "输出当前websocket所有用户"),
CHATToWEBGroup("4", "发送给web组");
public final String type;
public final String content;
MsgActionEnum(String type, String content){
this.type = type;
this.content = content;
}
public String getType() {
return type;
}
}

View File

@@ -0,0 +1,41 @@
package com.huashi.handle;
import com.huashi.websocket.UserChannelGroup;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* @Description: 用于检测channel的心跳handler
* 继承ChannelInboundHandlerAdapter从而不需要实现channelRead0方法
*/
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// 判断evt是否是IdleStateEvent用于触发用户事件包含 读空闲/写空闲/读写空闲
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent)evt; // 强制类型转换
if (event.state() == IdleState.READER_IDLE) {
//System.out.println("进入读空闲...");
} else if (event.state() == IdleState.WRITER_IDLE) {
//System.out.println("进入写空闲...");
} else if (event.state() == IdleState.ALL_IDLE) {
// TODO 用户掉线
System.out.println("channel关闭前users的数量为" + UserChannelGroup.users.size());
Channel channel = ctx.channel();
// 关闭无用的channel以防资源浪费
channel.close();
System.out.println("channel关闭后users的数量为" + UserChannelGroup.users.size());
}
}
}
}

View File

@@ -0,0 +1,39 @@
package com.huashi.handle;
import com.alibaba.fastjson.JSONObject;
import com.huashi.dto.DataContent;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.huashi.websocket.UserChannelRel;
import org.springframework.stereotype.Service;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Slf4j
public class SocketMsgTransfer {
//发送给单一key
public static void sendToSingleClient(String key, DataContent dataContent){
Channel findChannel = UserChannelRel.get(key);
if (findChannel != null) {
findChannel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(dataContent)));
}
}
// 发送给所有的web端通过前缀来匹配
public static void sendToRoleGroupClientByPrefixKey(String prefixKey, String role,DataContent dataContent){
log.info("===========================SocketMsgTransfer sendToRoleGroupClientByPrefixKey");
//TODO 方法有误,需要重写
List<Channel> channelList = UserChannelRel.getByPrefix(prefixKey);
for (Channel channel:channelList){
channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(dataContent)));
}
}
}

View File

@@ -0,0 +1,173 @@
package com.huashi.handle;
import com.alibaba.fastjson.JSONObject;
import com.huashi.dto.DataContent;
import com.huashi.enums.ConnectRoleEnum;
import com.huashi.enums.MsgActionEnum;
import com.huashi.utils.JsonUtils;
import com.huashi.websocket.UserChannelGroup;
import com.huashi.websocket.UserChannelRel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class SocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("======================= 收到新消息,消息接收完成");
super.channelReadComplete(ctx);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) {
System.out.println("======================= 收到新消息");
// 获取客户端传输过来的消息
String content = textWebSocketFrame.text();
log.info(content);
Channel currentChannel = ctx.channel();
try {
// 1. 获取客户端发来的消息
DataContent dataContent = JSONObject.parseObject(content, DataContent.class);
log.info(dataContent.getAction());
log.info(dataContent.getRole());
log.info(dataContent.getData());
if (dataContent.getAction().equals(MsgActionEnum.CONNECT.type)) {
//action 为1表示登录操作
this.loginAction(dataContent, currentChannel);
} else if (dataContent.getAction().equals(MsgActionEnum.CHAT.type)) {
//action 为2表示 发送给对方群组
dataContent.setCode("1");
if (StringUtils.equals(dataContent.getRole(), ConnectRoleEnum.UE.type)) {
String toConnectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-" + ConnectRoleEnum.WEB.type;
SocketMsgTransfer.sendToRoleGroupClientByPrefixKey(toConnectionId,ConnectRoleEnum.WEB.type,dataContent);
} else if (StringUtils.equals(dataContent.getRole(), ConnectRoleEnum.WEB.type)) {
String toConnectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-" + ConnectRoleEnum.UE.type;
SocketMsgTransfer.sendToRoleGroupClientByPrefixKey(toConnectionId,ConnectRoleEnum.UE.type,dataContent);
}
}else if(dataContent.getAction().equals(MsgActionEnum.CHATToCurrentUserGroup.type)){
log.info("================================ MsgActionEnum.CHATToCurrentUserGroup.type handler");
//action 为3表示 发送给当前用户所在群组
String toConnectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-"+dataContent.getRole();
SocketMsgTransfer.sendToRoleGroupClientByPrefixKey(toConnectionId,dataContent.getRole(),dataContent);
}else if(dataContent.getAction().equals(MsgActionEnum.CHATUSERLISTINFO.type)){
log.info("================================ MsgActionEnum.CHATToCurrentUserGroup.type handler");
//action 为3表示 发送给当前用户所在群组
String toConnectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-"+dataContent.getRole()+"-"+dataContent.getClientId();
dataContent.setRole(ConnectRoleEnum.SERVER.type);
dataContent.setData(JSONObject.toJSONString(UserChannelRel.getUserListInfo()));
SocketMsgTransfer.sendToSingleClient(toConnectionId,dataContent);
}
} catch (Exception e) {
log.info("=================================== SocketServerHandler error");
log.info(e.getMessage());
e.printStackTrace();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
/**
* 当客户端连接服务端之后(打开连接)
* 获取客户端的channle并且放到ChannelGroup中去进行管理
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("=================客户端加入channelId为" + ctx.channel().id().asShortText());
UserChannelGroup.users.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
String channelId = ctx.channel().id().asLongText();
UserChannelRel.removeByChannel(ctx.channel());
System.out.println("=================客户端被移除channelId为" + channelId);
// 当触发handlerRemovedChannelGroup会自动移除对应客户端的channel
UserChannelGroup.users.remove(ctx.channel());
System.out.println("=================打印当前存储的通道");
UserChannelRel.output();
}
public void loginAction(DataContent dataContent, Channel currentChannel) {
String role=dataContent.getRole();
UserChannelRel.output();
System.out.println("=======================================");
dataContent.setData("login ok");
dataContent.setCode("1");
if (StringUtils.equals(role, ConnectRoleEnum.UE.type)) {
String connectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-" + dataContent.getRole();
UserChannelRel.put(connectionId, currentChannel);
}
if (StringUtils.equals(role, ConnectRoleEnum.WEB.type)) {
String connectionId = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-" + dataContent.getRole()+"-"+dataContent.getClientId();
UserChannelRel.put(connectionId, currentChannel);
log.info("==================web端口登录判断UE是否存在");
String connectionUE = dataContent.getAppId() + "-" + dataContent.getSessionId() + "-" + ConnectRoleEnum.UE.type;
dataContent.setRole(ConnectRoleEnum.SERVER.type);
dataContent.setCode("0");
dataContent.setData("引擎底板不在线!!!");
dataContent.setRole("server");
Channel channel = UserChannelRel.get(connectionUE);
if(channel==null){
log.info("==================web端口登录判断UE不存在发送通知");
//TODO 判断UE是否在线
SocketMsgTransfer.sendToSingleClient(connectionId,dataContent);
}
}
UserChannelRel.output();
}
}

View File

@@ -0,0 +1,115 @@
package com.huashi.utils;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class ArtemisPostTest {
/**
* 请根据自己的appKey和appSecret更换static静态块中的三个参数. [1 host]
* 如果你选择的是和现场环境对接,host要修改为现场环境的ip,https端口默认为443http端口默认为80.例如10.33.25.22:443 或者10.33.25.22:80
* appKey和appSecret请按照或得到的appKey和appSecret更改.
* TODO 调用前先要清楚接口传入的是什么是传入json就用doPostStringArtemis方法下载图片doPostStringImgArtemis方法
*/
static {
ArtemisConfig.host = "172.16.3.12";// 代理API网关nginx服务器ip端口
ArtemisConfig.appKey = "20271264";// 秘钥appkey
ArtemisConfig.appSecret = "DTu6EKR9IW8ESvuur50l";// 秘钥appSecret
}
/**
* 能力开放平台的网站路径
* TODO 路径不用修改,就是/artemis
*/
private static final String ARTEMIS_PATH = "/artemis";
/**
* 调用POST请求类型(application/json)接口,这里以入侵报警事件日志为例
* https://open.hikvision.com/docs/918519baf9904844a2b608e558b21bb6#e6798840
*
* @return
*/
public static String callPostStringApi(){
/**
* http://10.33.47.50/artemis/api/scpms/v1/eventLogs/searches
* 根据API文档可以看出来这是一个POST请求的Rest接口而且传入的参数值为一个json
* ArtemisHttpUtil工具类提供了doPostStringArtemis这个函数一共六个参数在文档里写明其中的意思因为接口是https
* 所以第一个参数path是一个hashmap类型请put一个key-valuequery为传入的参数body为传入的json数据
* 传入的contentType为application/jsonaccept不指定为null
* header没有额外参数可不传,指定为null
*
*/
final String getCamsApi = ARTEMIS_PATH +"/api/resource/v1/park/parkList";
Map<String, String> path = new HashMap<String, String>(2) {
{
put("https://", getCamsApi);//根据现场环境部署确认是http还是https
}
};
JSONObject jsonBody = new JSONObject();
jsonBody.put("pageNo", 1);
jsonBody.put("pageSize", 3);
String body = jsonBody.toJSONString();
String result =ArtemisHttpUtil.doPostStringArtemis(path,null,null,null,"application/json",null);// post请求application/json类型参数
return result;
}
/**
* 调用POST请求下载图片类型接口这里以获取访客记录中的图片接口为例
* https://open.hikvision.com/docs/a0a1a0a24701a00aa904f7b151f97410#f11f3208
*
* @return
*/
public static void callPostImgStringApi(){
/**
* http://10.33.47.50/api/visitor/v1/record/pictures
* 根据API文档可以看出来这是一个POST请求的Rest接口而且传入的参数值为一个json
* ArtemisHttpUtil工具类提供了doPostStringImgArtemis这个函数一共六个参数在文档里写明其中的意思因为接口是https
* 所以第一个参数path是一个hashmap类型请put一个key-valuequery为传入的参数body为传入的json数据
* 传入的contentType为application/jsonaccept不指定为null
* header没有额外参数可不传,指定为null
*
*/
final String VechicleDataApi = ARTEMIS_PATH +"/api/visitor/v1/record/pictures";
Map<String,String> path = new HashMap<String,String>(2){
{
put("http://",VechicleDataApi);
}
};
JSONObject jsonBody = new JSONObject();
jsonBody.put("svrIndexCode", "8907fd9d-d090-43d3-bb3a-3a4b10dd7219");
jsonBody.put("picUri", "/pic?0dd453i3c-e*046456451175m6ep=t=i2p*i=d1s*i3d0d*=*1b8i81f4747059503--bdf90a-855s5721z3b9i=1=");
String body = jsonBody.toJSONString();
System.out.println("body: "+body);
HttpResponse result =ArtemisHttpUtil.doPostStringImgArtemis(path,body,null,null,"application/json",null);
try {
HttpResponse resp = result;
if (200==resp.getStatusLine().getStatusCode()) {
HttpEntity entity = resp.getEntity();
InputStream in = entity.getContent();
System.out.println("下载成功");
}else{
System.out.println("下载出错");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String StringeResult = callPostStringApi();
System.out.println(StringeResult);
System.out.println("StringeResult结果示例: "+StringeResult);
}
}

View File

@@ -0,0 +1,23 @@
package com.huashi.utils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HuaSanHttp {
public static void main(String[] args) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope("172.16.2.220", 8080, "iMC RESTful Web Services"),
new UsernamePasswordCredentials("admin", "Qwer@123.com"));
//HttpGet get = new HttpGet("http://172.16.2.220:8080/imcrs/perf/monitor?devId=2&taskId=33");
HttpGet get = new HttpGet("http://172.16.2.220:8080/imcrs/perf/summaryData?taskId=49&devId=2");
get.addHeader("accept", "application/json");
HttpResponse response = client.execute(get);
System.out.println(EntityUtils.toString(response.getEntity()));
}
}

View File

@@ -0,0 +1,73 @@
package com.huashi.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
/**
* @Description: 自定义响应结构, 转换类
*/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
System.out.println("=================JsonProcessingException");
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
System.out.println("=================JsonProcessingException");
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,75 @@
package com.huashi.websocket;
import com.huashi.handle.HeartBeatHandler;
import com.huashi.handle.SocketServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class SocketServer {
/**
* netty服务监听端口
*/
@Value("${netty.port}")
private int port;
/**
* 主线程组数量
*/
@Value("${netty.bossThread}")
private int bossThread;
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(bossThread);
// 实际工作的线程组
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup) // 两个线程组加入进来
.channel(NioServerSocketChannel.class) // 配置为nio类型
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpServerCodec());
// //以块的方式来写的处理器
// ch.pipeline().addLast(new ChunkedWriteHandler());
//http数据在传输中是分段将段聚合起来
ch.pipeline().addLast(new HttpObjectAggregator(65536*10000));
// ch.pipeline().addLast(new LengthFieldBasedFrameDecoder());
ch.pipeline().addLast(new HeartBeatHandler());
ch.pipeline().addLast(new SocketServerHandler());
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/hs-core",null,false,65536*10000));
}
}).option(ChannelOption.SO_BACKLOG,128).childOption(ChannelOption.SO_KEEPALIVE,true); // 加入自己的初始化器
ChannelFuture f=bootstrap.bind(port).sync();
System.out.println("=======================ok");
f.channel().closeFuture().sync();
}
public static void main(String[] args) throws Exception {
new SocketServer().start();
}
}

View File

@@ -0,0 +1,11 @@
package com.huashi.websocket;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
public class UserChannelGroup {
final public static ChannelGroup users =
new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}

View File

@@ -0,0 +1,71 @@
package com.huashi.websocket;
import io.netty.channel.Channel;
import java.util.*;
/**
* @Description: 用户id和channel的关联关系处理
*/
public class UserChannelRel {
private static Map<String, Channel> manager = new HashMap<>();
public static void put(String senderId, Channel channel) {
manager.put(senderId, channel);
output();
}
public static Channel get(String senderId) {
return manager.get(senderId);
}
/**
*
*
* */
public static List<Channel> getByPrefix(String prefix) {
List<Channel> channelList=new ArrayList<Channel>();
Iterator<Map.Entry<String, Channel>> it = manager.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, Channel> entry=it.next();
if(entry.getKey().contains(prefix)){
System.out.println(entry.getKey());
channelList.add(entry.getValue());
}
}
return channelList;
}
public static List<String> getUserListInfo(){
List<String> channelList=new ArrayList<String>();
for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
channelList.add(entry.getKey());
}
return channelList;
}
public static void output() {
System.out.println("=========================== 当前在线用户有: ===========================");
for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
System.out.println("UserId: " + entry.getKey()
+ ", ChannelId: " + entry.getValue().id().asLongText());
}
}
public static void removeByChannel(Channel channel){
//TODO
Iterator<Map.Entry<String, Channel>> it = manager.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, Channel> entry=it.next();
if(entry.getValue()==channel){
it.remove();
}
}
}
}

View File

@@ -0,0 +1,8 @@
server:
port: 28080
netty:
# netty服务监听端口
port: 8089
# 主线程组数量
bossThread: 1