Commit cd38a6d8 authored by AfirSraftGarrier's avatar AfirSraftGarrier

删除不必要

parent 07cc763c
......@@ -9,7 +9,7 @@
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sixiang.iot</groupId>
<artifactId>license</artifactId>
<artifactId>server-license</artifactId>
<version>1.0-SNAPSHOT</version>
<name>server-license</name>
<description>Demo project for Spring Boot</description>
......
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/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed.
@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%
<?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.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>iot.sixiang</groupId>
<artifactId>proxy_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>proxy_service</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-web</artifactId>
</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.33.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package iot.sixiang.proxy_service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProxyServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProxyServiceApplication.class, args);
}
}
package iot.sixiang.proxy_service;
import iot.sixiang.proxy_service.device.DeviceManager;
import iot.sixiang.proxy_service.forward.ForwardManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
//@Component
public class ProxyServiceCommandListener implements CommandLineRunner {
@Autowired
DeviceManager deviceManager;
@Autowired
ForwardManager forwardManager;
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
try {
deviceManager.init();
forwardManager.init();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.consts;
import java.io.File;
import java.util.HashMap;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
public class Consts {
public static final int CMD_LICENSE = 16;//授权消息的cmd,十进制
public static final int EXECUTOR_THREAD_NUM = 30;
public static final Integer DEVICE_STATE_ONLINE = 1;// 设备在线
public static final Integer DEVICE_STATE_OFFLINE = 0;// 设备离线
public static final Integer DEVICE_STATE_FAILURE = -1;// 设备故障
}
package iot.sixiang.proxy_service.device;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import iot.sixiang.proxy_service.consts.Consts;
import iot.sixiang.proxy_service.net.BaseChannelInitializer;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
@Slf4j
public class DeviceChannelInitializer extends BaseChannelInitializer {
private DeviceServerHandler handler;
static final EventExecutorGroup workGroup = new DefaultEventExecutorGroup(Consts.EXECUTOR_THREAD_NUM);
public DeviceChannelInitializer(DeviceServerHandler handler) {
this.handler = handler;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 服务端心跳检测
ch.pipeline().addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));
ch.pipeline().addLast("decoder", new DeviceDecoder());
ch.pipeline().addLast("encoder", new DeviceEncoder());
ch.pipeline().addLast(workGroup, "handler", handler);
}
}
package iot.sixiang.proxy_service.device;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/**
* 数据包格式
* STX |LEN |CMD |ACK |DATA |END
*/
@Slf4j
public class DeviceDecoder extends ByteToMessageDecoder {
public final int BASE_LENGTH = 2 + 2 + 1 + 1;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
try {
if (buffer.readableBytes() < BASE_LENGTH) {
return;
}
buffer.markReaderIndex();
short stx = buffer.readShort();//55AA->21930
short len = buffer.readShortLE();
// char cmd = buffer.readChar();
// char ack = buffer.readChar();//stx:21930,len:52,cmd:退,ack:ꭵ
// short cmd = buffer.readUnsignedByte();
// short ack = buffer.readUnsignedByte();//stx:21930,len:52,cmd:144,ack:0
// byte cmd = buffer.readByte();
// byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
// int cmd2 = cmd & 0xFF;
// int ack2 = ack & 0xFF;//stx:21930,len:52,cmd:144,ack:0
// byte[] cmd_bytes = new byte[1];
// buffer.readBytes(cmd_bytes);
// String cmd = new String(cmd_bytes, 0, cmd_bytes.length);
//
// byte[] ack_bytes = new byte[1];
// buffer.readBytes(ack_bytes);
// String ack = new String(ack_bytes, 0, ack_bytes.length);//: stx:21930,len:52,cmd:�,ack:
log.debug("stx:"+stx+",len:"+len+",cmd:"+cmd+",ack:"+ack);//stx:21930,len:52,cmd:-112,ack:0
int real_len = len + 1;
int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len-cmd_ack_len) {
buffer.resetReaderIndex();
return;
}
// buffer.resetReaderIndex();
byte[] content = new byte[real_len-cmd_ack_len];
buffer.readBytes(content);
DeviceProtocol protocol = new DeviceProtocol(stx, len,cmd,ack, content);
out.add(protocol);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("DeviceDecoder error!");
}
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.device;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* 数据包格式
* STX |LEN |CMD |ACK |DATA |END
*/
@Slf4j
public class DeviceEncoder extends MessageToByteEncoder<DeviceProtocol> {
@Override
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception {
try {
out.writeShort(msg.getStx());
out.writeShortLE(msg.getLen());
out.writeByte(msg.getCmd());
out.writeByte(msg.getAck());
if (msg.getContent() == null) {
// log.debug("body数据为空");
} else {
out.writeBytes(msg.getContent());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package iot.sixiang.proxy_service.device;
import iot.sixiang.proxy_service.model.SessionContext;
import iot.sixiang.proxy_service.net.TcpServer;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Title: DeviceManager
* Description: TODO
*
* @author m33
* @version V1.0
* @date 2022-06-04
*/
@Component
@Slf4j
public class DeviceManager {
private Map<String, SessionContext> sessionContexts = null;
private DeviceChannelInitializer channelInitializer;
private TcpServer server = null;
private int port = 18889;
@Autowired
private DeviceServerHandler handler;
@Getter
@Setter
SessionContext sessionContext = null;
public DeviceManager() {
sessionContexts = new HashMap<String, SessionContext>();
}
@PostConstruct
public void init() {
startTcpService();
}
private void startTcpService() {
log.debug("tcp server start......,prot:" + port);
sessionContexts = new HashMap<String, SessionContext>();
channelInitializer = new DeviceChannelInitializer(handler);
server = new TcpServer(port, channelInitializer);
server.start();
}
public SessionContext getSessionByRemoteIp(String remoteIp, int remotePort) {
SessionContext session = null;
Iterator<Map.Entry<String, SessionContext>> it = sessionContexts.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, SessionContext> entry = it.next();
SessionContext targetSession = entry.getValue();
if (targetSession.getRemoteIp().equals(remoteIp) && targetSession.getRemotePort() == remotePort) {
return targetSession;
}
}
return session;
}
public SessionContext getSessionByClientIp(String remoteIp, int remotePort) {
SessionContext session = null;
Iterator<Map.Entry<String, SessionContext>> it = sessionContexts.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, SessionContext> entry = it.next();
SessionContext targetSession = entry.getValue();
if (targetSession.getRemoteIp().equals(remoteIp) && targetSession.getRemotePort() == remotePort) {
return targetSession;
}
}
return session;
}
public synchronized void putSession(String deviceCode, SessionContext session) {
sessionContexts.put(deviceCode, session);
}
public SessionContext getSessionContextByDeviceCode(String deviceCode) {
return sessionContexts.get(deviceCode);
}
public synchronized boolean removeSession(String deviceCode, int offPort) {
if (sessionContexts.containsKey(deviceCode)) {
SessionContext session = sessionContexts.get(deviceCode);
if (session.getRemotePort() == offPort) {
sessionContexts.remove(deviceCode);
return true;
} else {
log.warn("client disconnect has a warning!");
return false;
}
} else {
log.warn("client disconnect,don't found the session");
return false;
}
}
}
package iot.sixiang.proxy_service.device;
import lombok.Data;
@Data
public class DeviceProtocol {
// |STX |LEN |CMD |ACK |DATA |END
private short stx;//
private int len;//
private byte cmd;
private byte ack;
private byte[] content;// 数据
public DeviceProtocol(short stx, int len,byte cmd,byte ack, byte[] content) {
super();
this.stx = stx;
this.len = len;
this.cmd = cmd;
this.ack = ack;
this.content = content;
}
@Override
public String toString() {
return "DeviceProtocol [stx=" + stx + ", len=" + len +",cmd="+cmd+",ack="+ack+ ", content="
+ new String(content, 0, content.length) + "]";
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.device;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import iot.sixiang.proxy_service.consts.Consts;
import iot.sixiang.proxy_service.forward.ForwardManager;
import iot.sixiang.proxy_service.license.LicenseManager;
import iot.sixiang.proxy_service.model.SessionContext;
import iot.sixiang.proxy_service.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
@Component
@ChannelHandler.Sharable
@Slf4j
public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
private byte[] obj = new byte[0]; // 特殊的instance变量
public DeviceServerHandler() {
super();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
SocketChannel channel = (SocketChannel) ctx.channel();
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String remoteIp = socketAddr.getHostString();
int remotePort = socketAddr.getPort();
DeviceProtocol protocol = (DeviceProtocol) msg;
log.debug("channel.id().asLongText():"+channel.id().asLongText());
// SessionContext session = new SessionContext();
// session.setClientIp(clientIp);
// session.setPort(clientPort);
// session.setClientChannel(channel);
// DeviceManager deviceManager= SpringUtil.getBean(DeviceManager.class);
// deviceManager.setSessionContext(session);
//
// //TODO:透传
// ForwardManager forwardManager= SpringUtil.getBean(ForwardManager.class);
// log.debug("channelRead0.forwardManager:"+forwardManager);
// log.debug("channelRead0.forwardManager.getClientChannel:"+forwardManager.getSessionContexts().getClientChannel());
// forwardManager.getSessionContexts().getClientChannel().writeAndFlush(protocol);
// short stx = buf.readShort();//55AA->21930
// short len = buf.readShortLE();
// log.debug("stx:"+stx+",len:"+len);
// log.debug("stx:"+stx+",len:"+len);
// channel.writeAndFlush(protocol);
/*
TODO:
1.透传前先进行鉴权
2.鉴权通过后,创建桥接客户端,非鉴权消息全部放行
3.未鉴权的不能进行透传,强制下线
*/
byte cmd = protocol.getCmd();
int cmdInt = cmd & 0xFF;
boolean license = false;
if (cmdInt == Consts.CMD_LICENSE){
license = handlerLicense(channel, remoteIp,remotePort, protocol);
}else {
license = handlerCheckLicense(channel, remoteIp,remotePort, protocol);
if(license){
handlerForward(channel, remoteIp,remotePort, protocol);
}
}
if(license==false){
channel.close();
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelRegistered(ctx);
log.debug("client channelRegistered");
log.debug("channel.id().asLongText():"+ctx.channel().id().asLongText());
}
@Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("client connected,ip:" + clientIp + ",port:" + port);
log.debug("channel.id().asLongText():"+ctx.channel().id().asLongText());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelInactive(ctx);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
DeviceManager deviceManager= SpringUtil.getBean(DeviceManager.class);
SessionContext session = deviceManager.getSessionByClientIp(clientIp, port);
if (session == null) {
return;
}
boolean result = deviceManager.removeSession(session.getDeviceCode(), port);
if (result) {
// TODO 设备离线需要中断该设备对应的中转客户端
}
log.debug("channel.id().asLongText():"+ctx.channel().id().asLongText());
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelReadComplete(ctx);
log.debug("client channelReadComplete");
log.debug("channel.id().asLongText():"+ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
cause.printStackTrace();
ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
}
@Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
if (obj instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) obj;
if (IdleState.READER_IDLE.equals(event.state())) { // 如果读通道处于空闲状态,说明没有接收到心跳命令
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
// synchronized (obj) {
// SessionContext session = deviceManager.getSessionByClientIp(clientIp, port);
// if (session == null) {
// log.warn("这是非法的连接");
// ctx.channel().close();
// } else {
//
//
// String deviceCode = session.getDeviceCode();
//
// int idleCount = session.getIdleCount();
// idleCount += 1;
// if (idleCount >= 1) {
// ctx.channel().close();
// session.setIdleCount(0);
// boolean result = deviceManager.removeSession(deviceCode, port, false);
// if (result) {
//// // TODO 设备离线需要上报设备状态给业务平台
//// // TODO 使用心跳检测判断掉线,可能存在多个线程监控一台设备是否重连上来,导致重复发送多次告警
////
//
//
// log.info(deviceCode + "," + "," + session.getClientIp() + ","
// + session.getPort() + ",心跳检测失败,异常下线");
// }
// }
// }
// }
}
} else {
super.userEventTriggered(ctx, obj);
}
}
private boolean handlerLicense(SocketChannel channel, String remoteIp,int remotePort, DeviceProtocol protocol) {
String jsonLicense = new String(protocol.getContent(), 0, protocol.getContent().length);
String deviceCode = "123456";
String deviceKey = "123456";
String token = "123456";
String channelId = channel.id().asLongText();
LicenseManager licenseManager = SpringUtil.getBean(LicenseManager.class);
boolean license = licenseManager.checkLicense(deviceCode,deviceKey);
if (license){
SessionContext session = new SessionContext();
session.setRemoteIp(remoteIp);
session.setRemotePort(remotePort);
session.setDeviceCode(deviceCode);
session.setDeviceKey(deviceKey);
session.setToken(token);
session.setChannelId(channelId);
session.setClientChannel(channel);
DeviceManager deviceManager= SpringUtil.getBean(DeviceManager.class);
deviceManager.putSession(deviceCode,session);
}
return license;
}
private boolean handlerCheckLicense(SocketChannel channel, String remoteIp, int remotePort, DeviceProtocol protocol) {
String channelId = channel.id().asLongText();
LicenseManager licenseManager = SpringUtil.getBean(LicenseManager.class);
// boolean license = licenseManager.checkLicense(deviceCode,deviceKey);
boolean license = false;
return license;
}
private void handlerForward(SocketChannel channel, String remoteIp,int remotePort, DeviceProtocol protocol) {
ForwardManager forwardManager = SpringUtil.getBean(ForwardManager.class);
log.debug("channelRead0.forwardManager:"+forwardManager);
log.debug("channelRead0.forwardManager.getClientChannel:"+forwardManager.getSessionContexts().getClientChannel());
forwardManager.getSessionContexts().getClientChannel().writeAndFlush(protocol);
}
}
package iot.sixiang.proxy_service.forward;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import iot.sixiang.proxy_service.consts.Consts;
import iot.sixiang.proxy_service.device.DeviceDecoder;
import iot.sixiang.proxy_service.device.DeviceEncoder;
import iot.sixiang.proxy_service.net.BaseChannelInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ForwardChannelInitializer extends BaseChannelInitializer {
static Logger logger = LoggerFactory.getLogger(ForwardChannelInitializer.class.getName());
private ForwardClientHandler handler;
static final EventExecutorGroup workGroup = new DefaultEventExecutorGroup(Consts.EXECUTOR_THREAD_NUM);
public ForwardChannelInitializer(ForwardClientHandler handler) {
this.handler = handler;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 服务端心跳检测
// ch.pipeline().addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS));
ch.pipeline().addLast("decoder", new ForwardDecoder());
ch.pipeline().addLast("encoder", new ForwardEncoder());
ch.pipeline().addLast(workGroup, "handler", handler);
}
}
package iot.sixiang.proxy_service.forward;
import iot.sixiang.proxy_service.net.TcpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class ForwardClient {
private TcpClient client = null;
private ForwardChannelInitializer channelInitializer;
@Autowired
ForwardClientHandler handler;
@Autowired
ForwardConnectionListener listener;
public ForwardClient() {
log.debug("ProxyNodeClient ProxyNodeClientHandler*****" + handler);
}
public void startTcp(String host, int port) {
log.debug("begin connect the server " + host + ",port " + port);
channelInitializer = new ForwardChannelInitializer(handler);
client = new TcpClient(host, port, channelInitializer, listener);
client.start();
}
}
package iot.sixiang.proxy_service.forward;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.proxy_service.device.DeviceManager;
import iot.sixiang.proxy_service.device.DeviceProtocol;
import iot.sixiang.proxy_service.model.SessionContext;
import iot.sixiang.proxy_service.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
@Component
@ChannelHandler.Sharable
@Slf4j
public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
// @Autowired
// ForwardManager forwardManager;
private byte[] obj = new byte[0]; // 特殊的instance变量
private String nodeType = "rsretail";
public ForwardClientHandler() {
super();
log.debug("ProxyNodeClientHandler ****");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
// 用于获取客户端发来的数据信息
SocketChannel channel = (SocketChannel) ctx.channel();
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String serverIp = socketAddr.getHostString();
int serverPort = socketAddr.getPort();
log.debug("channelRead0...");
DeviceProtocol protocol = (DeviceProtocol) msg;
log.debug("准备发回给设备:"+protocol.toString());
DeviceManager deviceManager= SpringUtil.getBean(DeviceManager.class);
deviceManager.getSessionContext().getClientChannel().writeAndFlush(protocol);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
// TODO Auto-generated method stub
try {
super.channelRegistered(ctx);
log.debug("channelRegistered----------->");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelActive********");
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
SessionContext session = new SessionContext();
session.setRemoteIp(clientIp);
session.setRemotePort(port);
session.setClientChannel(channel);
ForwardManager forwardManager= SpringUtil.getBean(ForwardManager.class);
log.debug("channelActive.getClientChannel:"+channel);
forwardManager.setSessionContexts(session);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelInactive(ctx);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("client disconnected--->,ip:" + clientIp + ",port:" + port);
ctx.close();
ForwardManager forwardManager= SpringUtil.getBean(ForwardManager.class);
forwardManager.startTcpClient();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelReadComplete(ctx);
log.debug("channelReadComplete");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
cause.printStackTrace();
ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
}
@Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("userEventTriggered");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package iot.sixiang.proxy_service.forward;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import iot.sixiang.proxy_service.net.BaseConnectionListener;
import iot.sixiang.proxy_service.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class ForwardConnectionListener extends BaseConnectionListener {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (!channelFuture.isSuccess()) {
final EventLoop loop = channelFuture.channel().eventLoop();
loop.schedule(new Runnable() {
@Override
public void run() {
log.debug("ForwardConnectionListener ...operationComplete");
ForwardManager forwardManager= SpringUtil.getBean(ForwardManager.class);
log.debug("channelActive.forwardManager:"+forwardManager);
log.warn("The client is not connected and starts to reconnect..."+ forwardManager);
forwardManager.startTcpClient();
}
}, 10L, TimeUnit.SECONDS);
} else {
log.debug("Successful connection to the server");
}
}
}
package iot.sixiang.proxy_service.forward;
import java.util.List;
import iot.sixiang.proxy_service.device.DeviceProtocol;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
/**
* <pre>
*
* 自己定义的协议
* 数据包格式
* |类型 |序号|返回码|长度|连接标识|设备编码|数据|
* </pre>
*/
@Slf4j
public class ForwardDecoder extends ByteToMessageDecoder {
public final int BASE_LENGTH = 2 + 2 + 1+1;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
// 可读长度必须大于等于基本长度
try {
if (buffer.readableBytes() < BASE_LENGTH) {
return;
}
buffer.markReaderIndex();
short stx = buffer.readShort();//55AA->21930
short len = buffer.readShortLE();
byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
log.debug("stx:"+stx+",len:"+len);
int real_len = len;//注意,透传前已经去掉了END一个字符
int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len-cmd_ack_len) {
buffer.resetReaderIndex();
return;
}
// buffer.resetReaderIndex();//复位
// 读取data数据
byte[] content = new byte[real_len-cmd_ack_len];
buffer.readBytes(content);
log.debug("ForwardDecoder.msg.getLen()...."+real_len);
DeviceProtocol protocol = new DeviceProtocol(stx, real_len,cmd,ack, content);
out.add(protocol);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("DeviceDecoder error!");
}
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.forward;
import iot.sixiang.proxy_service.device.DeviceProtocol;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* <pre>
*
* 自己定义的协议
* 数据包格式
* |类型 |序号|返回码|长度|连接标识|设备编码|数据|
* </pre>
*/
@Slf4j
public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
@Override
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception {
try {
// short stx = in.readShort();//55AA->21930
// short len = in.readShortLE();
out.writeShort(msg.getStx());
// out.writeShort(msg.getLen());
out.writeShortLE(msg.getLen());
out.writeByte(msg.getCmd());
out.writeByte(msg.getAck());
log.debug("ForwardEncoder.msg.getLen()...."+msg.getLen());
if (msg.getContent() == null) {
// logger.debug("body数据为空");
} else {
out.writeBytes(msg.getContent());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error("DeviceEncoder error---->");
}
}
}
package iot.sixiang.proxy_service.forward;
import iot.sixiang.proxy_service.model.SessionContext;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component(value = "forwardManager")
@Slf4j
public class ForwardManager {
static Logger logger = LoggerFactory.getLogger(ForwardManager.class.getName());
String serviceIP = "121.46.25.14";
int port = 18889;
@Autowired
public ForwardClient client;
@Getter
@Setter
SessionContext sessionContexts = null;
public ForwardManager() {
super();
}
// @PostConstruct
public void init() {
startTcpClient();
}
public void startTcpClient() {
client.startTcp(serviceIP, port);
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.forward;
import java.io.UnsupportedEncodingException;
import lombok.Data;
/**
* <pre>
*
* 自己定义的协议
* 数据包格式
*|类型 |序号|返回码|连接标识|设备编码|长度|数据|
* </pre>
*/
@Data
public class ForwardProtocol {
private int type;// 类型
private int seq;// 序号
private int length;// 长度
private byte[] content;// 数据
public ForwardProtocol(int type, int seq, int length,
byte[] content) {
super();
this.type = type;
this.seq = seq;
this.length = length;
this.content = content;
}
@Override
public String toString() {
return "ForwardProtocol [type=" + type + ", seq=" + seq
+ ", length=" + length + ", content="
+ new String(content, 0, content.length) + "]";
}
}
\ No newline at end of file
package iot.sixiang.proxy_service.license;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
/**
* Title: LicenseManager
* Description: TODO
*
* @author m33
* @version V1.0
* @date 2022-06-05
*/
@Component
@Slf4j
public class LicenseManager {
public LicenseManager(){
}
@PostConstruct
public void init(){
}
public boolean checkLicense(String deviceCode,String deviceKey){
if(deviceCode.equals("123456")&&deviceKey.equals("123456")){
return true;
}else{
return false;
}
}
}
package iot.sixiang.proxy_service.model;
import java.io.Serializable;
import lombok.Data;
@Data
public class Device implements Serializable{
private String device_code;
private String device_name;
private String pass_code;
private int device_status;//0 offline,1 online
}
package iot.sixiang.proxy_service.model;
import io.netty.channel.socket.SocketChannel;
import lombok.Data;
@Data
public class SessionContext {
private String remoteIp;
private int remotePort;
private String deviceCode;//设备序列号
private String deviceKey;//设备key/授权ID
private String token;//连接标识
private int device_status;//0 offline,1 online
private String channelId;
private SocketChannel clientChannel;
}
package iot.sixiang.proxy_service.net;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
public class BaseChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
}
}
package iot.sixiang.proxy_service.net;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
public class BaseConnectionListener implements ChannelFutureListener {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
// TODO Auto-generated method stub
}
}
package iot.sixiang.proxy_service.net;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
public class MySSLContext {
static Logger logger = LoggerFactory.getLogger(MySSLContext.class.getName());
private static SSLContext sslContext;
public static SSLContext getSSLContext(String serverKeystorePath, String serverKeystorePwd,
String tserverKeystorePath, String serverTrustKeystorePwd) {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
keyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/kserver.keystore"),
serverKeystorePwd.toCharArray());
trustKeyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/tserver.keystore"),
serverTrustKeystorePwd.toCharArray());
/*
* keyStore.load(new FileInputStream(serverKeystorePath),
* serverKeystorePwd.toCharArray()); trustKeyStore.load(new
* FileInputStream(tserverKeystorePath),
* serverTrustKeystorePwd.toCharArray());
*/
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, serverKeystorePwd.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
trustManagerFactory.init(trustKeyStore);
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
// sslContext.init(keyManagerFactory.getKeyManagers(),null,
// null);
logger.debug("SSLContext init success");
} catch (KeyManagementException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return sslContext;
}
}
package iot.sixiang.proxy_service.net;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
public class MyX509TrustManager extends X509ExtendedTrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
}
package iot.sixiang.proxy_service.net;
public class NetMsgSeq {
private static short seq = 1;
public static synchronized short getSeq() {
if (seq > 65535) {
seq = 1;
}
seq++;
return seq;
}
}
package iot.sixiang.proxy_service.net;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.xiezuo.rsretail.node.ConnectionListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class TcpClient {
static Logger logger = LoggerFactory.getLogger(TcpClient.class);
private int port;
private String host;
private int index;
private BaseChannelInitializer channelInitializer;
private BaseConnectionListener connectionListener;
public TcpClient(String host, int port,BaseChannelInitializer channelInitializer,BaseConnectionListener connectionListener) {
this.host = host;
this.port = port;
this.channelInitializer = channelInitializer;
this.connectionListener = connectionListener;
}
public void start() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.group(eventLoopGroup)
.remoteAddress(host, port)
.handler(channelInitializer);
ChannelFuture future = bootstrap.connect(host, port);
future.addListener(connectionListener);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
}
}
package iot.sixiang.proxy_service.net;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class TcpServer {
static Logger logger = LoggerFactory.getLogger(TcpServer.class.getName());
private int port;
private BaseChannelInitializer channelInitializer;
public static Map<ChannelId, SocketChannel> clients = new LinkedHashMap<ChannelId, SocketChannel>();
public TcpServer(int port, BaseChannelInitializer channelInitializer) {
this.port = port;
this.channelInitializer = channelInitializer;
}
public void start() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup(4);
EventLoopGroup workerGroup = new NioEventLoopGroup(4);
logger.debug("begin open the port:" + port);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
// .handler(new LoggingHandler(LogLevel.INFO))
.childHandler(channelInitializer)
.option(ChannelOption.SO_BACKLOG, 1024) // 设置tcp缓冲区
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f;
try {
f = b.bind(port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
logger.debug("close the server");
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
});
thread.start();
}
}
package iot.sixiang.proxy_service.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
static Logger logger = LoggerFactory.getLogger(SpringUtil.class.getName());
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
logger.info(
"========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="
+ SpringUtil.applicationContext + "========");
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// // 通过name获取 Bean.
// public static Object getBean(String name) {
// return getApplicationContext().getBean(name);
// }
//
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//
// // 通过name,以及Clazz返回指定的Bean
// public static <T> T getBean(String name, Class<T> clazz) {
// return getApplicationContext().getBean(name, clazz);
// }
}
\ No newline at end of file
package iot.sixiang.proxy_service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProxyServiceApplicationTests {
@Test
void contextLoads() {
}
}
package iot.sixiang.proxy_service;
/**
* Title: Test
* Description: TODO
*
* @author m33
* @version V1.0
* @date 2022-06-05
*/
public class Test {
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static byte[] hexTobytes(String hex) {
if (hex.length() < 1) {
return null;
} else {
byte[] result = new byte[hex.length() / 2];
int j = 0;
for(int i = 0; i < hex.length(); i+=2) {
result[j++] = (byte)Integer.parseInt(hex.substring(i,i+2), 16);
}
return result;
}
}
public static void main(String[] args) {
byte[] src = new byte[1];
src[0] = -122;
String hex = bytesToHexString(src);
System.out.println(hex);
hex = "90";
byte[] bb = hexTobytes(hex);
int cc = bb[0] & 0xFF;
System.out.println(cc);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment