Commit 128f3a97 authored by zhushanglei's avatar zhushanglei

init

parents
Pipeline #254 failed with stages
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Zeppelin ignored files
/ZeppelinRemoteNotebooks/
<component name="ArtifactManager">
<artifact type="jar" name="GnssServer:jar">
<output-path>$PROJECT_DIR$/out/artifacts/GnssServer_jar</output-path>
<root id="archive" name="GnssServer.jar">
<element id="directory" name="META-INF">
<element id="file-copy" path="$PROJECT_DIR$/src/META-INF/MANIFEST.MF" />
</element>
<element id="module-output" name="GnssServer" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/io/netty/netty-all/4.1.34.Final/netty-all-4.1.34.Final.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/ch/qos/logback/logback-core/1.1.11/logback-core-1.1.11.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/fazecast/jSerialComm/2.9.1/jSerialComm-2.9.1.jar" path-in-jar="/" />
</root>
</artifact>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="GnssServer" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="central" />
<option name="url" value="http://central" />
</remote-repository>
<remote-repository>
<option name="id" value="public-snapshots" />
<option name="name" value="public-snapshots" />
<option name="url" value="http://public-snapshots" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
<component name="ProjectType">
<option name="id" value="jpab" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.0 r1840935">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
<stringProp name="TestPlan.comments"></stringProp>
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="TestPlan.user_define_classpath"></stringProp>
</TestPlan>
<hashTree>
<CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="CSV Data Set Config" enabled="false">
<stringProp name="delimiter">,</stringProp>
<stringProp name="fileEncoding"></stringProp>
<stringProp name="filename"></stringProp>
<boolProp name="ignoreFirstLine">false</boolProp>
<boolProp name="quotedData">false</boolProp>
<boolProp name="recycle">true</boolProp>
<stringProp name="shareMode">shareMode.all</stringProp>
<boolProp name="stopThread">false</boolProp>
<stringProp name="variableNames"></stringProp>
</CSVDataSet>
<hashTree/>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="TCP Test" enabled="false">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">2</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
</ThreadGroup>
<hashTree/>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="BinaryTCPClientImpl" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">1</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
</ThreadGroup>
<hashTree>
<UserParameters guiclass="UserParametersGui" testclass="UserParameters" testname="User Parameters" enabled="true">
<collectionProp name="UserParameters.names">
<stringProp name="-602535354">command1</stringProp>
</collectionProp>
<collectionProp name="UserParameters.thread_values">
<collectionProp name="55981015">
<stringProp name="1538">02</stringProp>
</collectionProp>
</collectionProp>
<boolProp name="UserParameters.per_iteration">false</boolProp>
</UserParameters>
<hashTree/>
<JSR223PreProcessor guiclass="TestBeanGUI" testclass="JSR223PreProcessor" testname="H16 PreProcessor" enabled="true">
<stringProp name="cacheKey">true</stringProp>
<stringProp name="filename"></stringProp>
<stringProp name="parameters"></stringProp>
<stringProp name="script">String command = &quot;${command1}&quot;;
log.info(command);
char[] h16 = &quot;0123456789abcdef&quot;.toCharArray();
StringBuilder tmp = new StringBuilder(&quot;&quot;);
byte[] bytes = command.getBytes();
int pos = 0;
for (int i = 0; i &lt; bytes.length; i++) {
pos = (bytes[i] &amp; 0x0f0) &gt;&gt; 4;
tmp.append(h16[pos]);
pos = bytes[i] &amp; 0x0f;
tmp.append(h16[pos]);
}
vars.put(&quot;HexCommand&quot;, tmp.toString().trim());
</stringProp>
<stringProp name="scriptLanguage">groovy</stringProp>
</JSR223PreProcessor>
<hashTree/>
<JSR223PostProcessor guiclass="TestBeanGUI" testclass="JSR223PostProcessor" testname="H16 PostProcessor" enabled="true">
<stringProp name="cacheKey">true</stringProp>
<stringProp name="filename"></stringProp>
<stringProp name="parameters"></stringProp>
<stringProp name="script">import org.apache.jmeter.samplers.SampleResult;
String h16 = &quot;0123456789abcdef&quot;;
String response_data = prev.getResponseDataAsString();
char[] hexs = response_data.toCharArray();
byte[] bytes = new byte[response_data.length()/2];
int pos = 0;
for(int i = 0; i &lt; bytes.length; i++){
pos = h16.indexOf(hexs[i*2] as int)*16;
pos += h16.indexOf(hexs[i*2+1] as int);
bytes[i] = (byte)(pos &amp; 0xff);
}
String responseData = (new String(bytes)).trim();
vars.put(&quot;response&quot;, responseData);</stringProp>
<stringProp name="scriptLanguage">groovy</stringProp>
</JSR223PostProcessor>
<hashTree/>
<TCPSampler guiclass="TCPSamplerGui" testclass="TCPSampler" testname="BinaryTCPClientImpl Sampler" enabled="true">
<stringProp name="TCPSampler.classname">BinaryTCPClientImpl</stringProp>
<stringProp name="TCPSampler.server">127.0.0.1</stringProp>
<boolProp name="TCPSampler.reUseConnection">true</boolProp>
<stringProp name="TCPSampler.port">9999</stringProp>
<boolProp name="TCPSampler.nodelay">false</boolProp>
<stringProp name="TCPSampler.timeout">100</stringProp>
<stringProp name="TCPSampler.ctimeout">100</stringProp>
<stringProp name="TCPSampler.request">${HexCommand}</stringProp>
<boolProp name="TCPSampler.closeConnection">false</boolProp>
<stringProp name="TCPSampler.EolByte">10</stringProp>
<stringProp name="ConfigTestElement.username"></stringProp>
<stringProp name="ConfigTestElement.password"></stringProp>
</TCPSampler>
<hashTree/>
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
<boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp>
<name>saveConfig</name>
<value class="SampleSaveConfiguration">
<time>true</time>
<latency>true</latency>
<timestamp>true</timestamp>
<success>true</success>
<label>true</label>
<code>true</code>
<message>true</message>
<threadName>true</threadName>
<dataType>true</dataType>
<encoding>false</encoding>
<assertions>true</assertions>
<subresults>true</subresults>
<responseData>false</responseData>
<samplerData>false</samplerData>
<xml>false</xml>
<fieldNames>true</fieldNames>
<responseHeaders>false</responseHeaders>
<requestHeaders>false</requestHeaders>
<responseDataOnError>false</responseDataOnError>
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
<assertionsResultsToSave>0</assertionsResultsToSave>
<bytes>true</bytes>
<sentBytes>true</sentBytes>
<url>true</url>
<threadCounts>true</threadCounts>
<idleTime>true</idleTime>
<connectTime>true</connectTime>
</value>
</objProp>
<stringProp name="filename"></stringProp>
</ResultCollector>
<hashTree/>
<DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="Debug Sampler" enabled="true">
<boolProp name="displayJMeterProperties">false</boolProp>
<boolProp name="displayJMeterVariables">true</boolProp>
<boolProp name="displaySystemProperties">false</boolProp>
</DebugSampler>
<hashTree/>
<TCPSampler guiclass="TCPSamplerGui" testclass="TCPSampler" testname="TCP Sampler" enabled="false">
<stringProp name="TCPSampler.server">127.0.0.1</stringProp>
<boolProp name="TCPSampler.reUseConnection">true</boolProp>
<stringProp name="TCPSampler.port">9999</stringProp>
<boolProp name="TCPSampler.nodelay">false</boolProp>
<stringProp name="TCPSampler.timeout">100</stringProp>
<stringProp name="TCPSampler.ctimeout">100</stringProp>
<stringProp name="TCPSampler.request">123</stringProp>
<boolProp name="TCPSampler.closeConnection">false</boolProp>
<stringProp name="TCPSampler.EolByte">10</stringProp>
<stringProp name="ConfigTestElement.username"></stringProp>
<stringProp name="ConfigTestElement.password"></stringProp>
</TCPSampler>
<hashTree/>
</hashTree>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="AccessLog Sampler" enabled="false">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">3</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
</ThreadGroup>
<hashTree>
<AccessLogSampler guiclass="TestBeanGUI" testclass="AccessLogSampler" testname="Access Log Sampler" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="domain">127.0.0.1</stringProp>
<boolProp name="imageParsing">false</boolProp>
<stringProp name="logFile">/Users/xs/Desktop/TesterHome/Demo/access.log</stringProp>
<stringProp name="parserClassName">org.apache.jmeter.protocol.http.util.accesslog.TCLogParser</stringProp>
<stringProp name="portString">8888</stringProp>
<stringProp name="filterClassName">org.apache.jmeter.protocol.http.util.accesslog.LogFilter</stringProp>
</AccessLogSampler>
<hashTree/>
</hashTree>
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
<boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp>
<name>saveConfig</name>
<value class="SampleSaveConfiguration">
<time>true</time>
<latency>true</latency>
<timestamp>true</timestamp>
<success>true</success>
<label>true</label>
<code>true</code>
<message>true</message>
<threadName>true</threadName>
<dataType>true</dataType>
<encoding>false</encoding>
<assertions>true</assertions>
<subresults>true</subresults>
<responseData>false</responseData>
<samplerData>false</samplerData>
<xml>false</xml>
<fieldNames>true</fieldNames>
<responseHeaders>false</responseHeaders>
<requestHeaders>false</requestHeaders>
<responseDataOnError>false</responseDataOnError>
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
<assertionsResultsToSave>0</assertionsResultsToSave>
<bytes>true</bytes>
<sentBytes>true</sentBytes>
<url>true</url>
<threadCounts>true</threadCounts>
<idleTime>true</idleTime>
<connectTime>true</connectTime>
</value>
</objProp>
<stringProp name="filename"></stringProp>
</ResultCollector>
<hashTree/>
</hashTree>
</hashTree>
</jmeterTestPlan>
127.0.0.1 - test [05/Dev/2019:13:55:36 +0700] "GET /index HTTP/1.0" 200 2326
127.0.0.1 - test [05/Dev/2018:13:55:50 +0700] "GET /about HTTP/1.0" 200 3358
127.0.0.1 - test [05/Dev/2018:13:56:15 +0700] "GET /profile HTTP/1.0" 200 4581
127.0.0.1 - test [05/Dev/2018:13:56:16 +0700] "GET /profile HTTP/1.0" 500 4581
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.minestar</groupId>
<artifactId>GnssServer</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>[2.0.0,3.0.0)</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.34.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.11</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
\ No newline at end of file
Manifest-Version: 1.0
Main-Class: server.TcpServer
package client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* @author yuli
* @ClassName TcpClient
**/
public class TcpClient {
public static String HOST = "127.0.0.1";
public static int PORT = 9200;
public static Bootstrap bootstrap = getBootstrap();
public static Channel channel = getChannel(HOST, PORT);
/**
* 初始化Bootstrap
*/
public static final Bootstrap getBootstrap() {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("handler", new TcpClientHandler());
}
});
b.option(ChannelOption.SO_KEEPALIVE, true);
return b;
}
// 连接端口
public static final Channel getChannel(String host, int port) {
Channel channel = null;
try {
channel = bootstrap.connect(host, port).sync().channel();
} catch (Exception e) {
System.out.println("Connect Server(IP{},PORT{}) Failed"+"host:"+host+"port:"+port+"e:"+e);
return null;
}
return channel;
}
/**
* 发送信息
* @param [msg]
* @return void
*/
public static void sendMsg(String msg) throws Exception {
if (channel != null) {
channel.writeAndFlush(msg).sync();
} else {
System.out.println("Msg Send Failed , Connection Lost!");
}
}
public static void main(String[] args) throws Exception {
try {
TcpClient.sendMsg("02");
} catch (Exception e) {
System.out.println("main err:"+ e);
}
}
}
package client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @author yuli
* @ClassName TcpClientHandler
**/
public class TcpClientHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("client receive msg from server:" + msg);
}
}
package server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* @author yuli
* @Description:TODO
* @ClassName TcpServer
**/
public class TcpServer {
// 服务器地址端口
private static final String IP = "192.168.0.111";
private static final int PORT = 9200;
/** 用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;
/** 业务出现线程大小 */
protected static final int BIZTHREADSIZE = 4;
/*
* NioEventLoopGroup实际上就是个线程池,
* NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
* 每一个NioEventLoop负责处理m个Channel,
* NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
*/
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
// 线程内容
protected static void run() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Decode是对发送的信息进行编码、
// @param maxFrameLength 帧的最大长度
// @param lengthFieldOffset length字段偏移的地址
// @param lengthFieldLength length字段所占的字节
// @param lengthAdjustment 修改帧数据长度字段中定义的值,
// 可以为负数 因为有时候我们习惯把头部记入长度,若为负数,则说明要推后多少个字段
// @param initialBytesToStrip 解析时候跳过多少个长度
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(new TcpServerHandler());
TcpServerHandler.openComm();
}
});
// 异步绑定端口
b.bind(IP, PORT).sync();
System.out.println("TCP Server Started");
}
// 关闭端口
protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
System.out.println("Starting TCP Server...");
TcpServer.run();
// TcpServer.shutdown();
}
}
package server;
import com.fazecast.jSerialComm.SerialPort;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author yuli
* @ClassName TcpServerHandler
**/
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
private Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);
/**
* 打印接收到的内容,并回传
// * @param [ctx, msg]
* @return void
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// logger.info(msg.toString());
System.out.println("**接收到的基站数据<<start:" + msg.toString() +">>end");
String writeData = msg.toString(); //要发送的字符串
byte[] bytes = writeData.getBytes();//将字符串转换为字节数组
writeComm(serialPort, bytes);
Thread.sleep(20);//休眠0.02秒,等待下位机传送数据到串口。如果不休眠,直接再次使用port.bytesAvailable()函数会因为下位机还没有返回数据而返回-1,并跳出循环导致数据没读完。休眠时间可以自行调试,时间越长,单次读取到的数据越多。
String result = readComm(serialPort);
System.out.println("**COM口读出数据<<start:" + result +">>end");
// if (msg.equals("01")){
// System.out.println("receive command :" + msg);
// ctx.channel().writeAndFlush("command 01 executed!\n");
// }else if(msg.equals("02")){
// System.out.println("receive command :" + msg);
// ctx.channel().writeAndFlush("command 02 executed!\n");
// }else {
// System.out.println("unknown command:" + msg);
// ctx.channel().writeAndFlush("unknown command!\n");
// }
}
private static SerialPort serialPort;
public static SerialPort openComm() {
SerialPort[] serialPorts = SerialPort.getCommPorts();//查找所有串口
for(SerialPort port:serialPorts){
System.out.println("PortName:"+port.getSystemPortName());//打印串口名称,如COM4
System.out.println("PortDesc:"+port.getPortDescription());//打印串口类型,如USB Serial
System.out.println("PortDescriptivePortName:"+port.getDescriptivePortName());//打印串口的完整类型,如USB-SERIAL CH340(COM4)
if(port.getSystemPortName().equalsIgnoreCase("COM1")){
serialPort = port;
}
}
serialPort.setBaudRate(115200);//设置波特率为112500
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
serialPort.setRTS();//设置RTS。也可以设置DTR
serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);//设置串口的控制流,可以设置为disabled,或者CTS, RTS/CTS, DSR, DTR/DSR, Xon, Xoff, Xon/Xoff等
serialPort.setComPortParameters(115200, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);//一次性设置所有的串口参数,第一个参数为波特率,默认9600;第二个参数为每一位的大小,默认8,可以输入5到8之间的值;第三个参数为停止位大小,只接受内置常量,可以选择(ONE_STOP_BIT, ONE_POINT_FIVE_STOP_BITS, TWO_STOP_BITS);第四位为校验位,同样只接受内置常量,可以选择 NO_PARITY, EVEN_PARITY, ODD_PARITY, MARK_PARITY,SPACE_PARITY。
if(!serialPort.isOpen()){
boolean isCommOpeded = serialPort.openPort();//判断串口是否打开,如果没打开,就打开串口。打开串口的函数会返回一个boolean值,用于表明串口是否成功打开了
System.out.println("COM口是否打开: "+ isCommOpeded);
}
// serialPort.closePort();//关闭串口。该函数同样会返回一个boolean值,表明串口是否成功关闭
return serialPort;
}
private void writeComm(SerialPort serialPort, byte[] data) throws InterruptedException {
if(serialPort == null || !serialPort.isOpen()){
System.out.println("COM口未打开");
return;
}
int result = serialPort.writeBytes(data,data.length);//将字节数组全部写入串口
if(result != -1){
System.out.println("COM口已成功写入数据");
}else{
System.out.println("COM口写数据失败");
}
}
private String readComm(SerialPort serialPort) {
if (serialPort == null || !serialPort.isOpen()) {
System.out.println("COM口未打开");
return null;
}
String readData = "";
while(serialPort.bytesAvailable()>0){ //循环读取所有的返回数据。如果可读取数据长度为0或-1,则停止读取
byte[] newData = new byte[serialPort.bytesAvailable()];//创建一个字节数组,长度为可读取的字节长度
int numRead = serialPort.readBytes(newData, newData.length);//将串口中可读取的数据读入字节数组,返回值为本次读取到的字节长度
String newDataString = new String(newData);//将新数据转为字符串
readData = readData + newDataString;//组合字符串
}
return readData;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exceptionCaught! cause:" + cause.toString());
ctx.close();
}
}
#Generated by Maven
#Wed Mar 30 16:31:59 CST 2022
version=1.0
groupId=com.yuli
artifactId=TCPServerDemo
F:\wokespace\NettyTcpServer-master\src\main\java\client\TcpClient.java
F:\wokespace\NettyTcpServer-master\src\main\java\client\TcpClientHandler.java
F:\wokespace\NettyTcpServer-master\src\main\java\server\TcpServerHandler.java
F:\wokespace\NettyTcpServer-master\src\main\java\server\TcpServer.java
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