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
This diff is collapsed.
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