Commit 369e781f authored by zhushanglei's avatar zhushanglei

init

parent 30167451
......@@ -12,6 +12,10 @@ 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
/**
* @author yuli
......@@ -20,8 +24,11 @@ import io.netty.util.CharsetUtil;
**/
public class TcpServer {
private static Logger logger = LoggerFactory.getLogger(TcpServer.class);
// 服务器地址端口
private static final String IP = "192.168.0.111";
// private static final String IP = "192.168.0.112";
// private static final String IP = "192.168.0.107";
private static final int PORT = 9200;
/** 用于分配处理业务线程的线程组个数 */
......@@ -62,8 +69,13 @@ public class TcpServer {
}
});
// 异步绑定端口
b.bind(IP, PORT).sync();
System.out.println("TCP Server Started");
InetAddress addr = InetAddress.getLocalHost();
logger.info("Local HostAddress:"+addr.getHostAddress());
String hostname = addr.getHostName();
logger.info("Local host name: "+hostname);
b.bind(addr.getHostAddress(), PORT).sync();
logger.info("TCP Server Started");
}
// 关闭端口
protected static void shutdown() {
......@@ -72,7 +84,7 @@ public class TcpServer {
}
public static void main(String[] args) throws Exception {
System.out.println("Starting TCP Server...");
logger.info("Starting TCP Server...");
TcpServer.run();
// TcpServer.shutdown();
}
......
......@@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory;
**/
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
private Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);
private static Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);
/**
* 打印接收到的内容,并回传
......@@ -21,20 +21,19 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// logger.info(msg.toString());
System.out.println("**接收到的基站数据<<start:" + msg.toString() +">>end");
logger.info("**接收到的基站数据<<start:" + msg.toString() +">>end");
String writeData = msg.toString(); //要发送的字符串
byte[] bytes = writeData.getBytes();//将字符串转换为字节数组
int flag = writeComm(serialPort, bytes);
if(-2 == flag){
openComm();
}
Thread.sleep(5000);//休眠0.02秒,等待下位机传送数据到串口。如果不休眠,直接再次使用port.bytesAvailable()函数会因为下位机还没有返回数据而返回-1,并跳出循环导致数据没读完。休眠时间可以自行调试,时间越长,单次读取到的数据越多。
Thread.sleep(500);//休眠0.02秒,等待下位机传送数据到串口。如果不休眠,直接再次使用port.bytesAvailable()函数会因为下位机还没有返回数据而返回-1,并跳出循环导致数据没读完。休眠时间可以自行调试,时间越长,单次读取到的数据越多。
String result = readComm(serialPort);
if(null == result){
openComm();
}
System.out.println("**COM口读出数据<<start:" + result +">>end");
logger.info("**COM口读出数据<<start:" + result +">>end");
}
private static SerialPort serialPort;
......@@ -56,7 +55,7 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
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);
logger.info("COM口是否打开: "+ isCommOpeded);
}
// serialPort.closePort();//关闭串口。该函数同样会返回一个boolean值,表明串口是否成功关闭
return serialPort;
......@@ -64,21 +63,21 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
private int writeComm(SerialPort serialPort, byte[] data) throws InterruptedException {
if(serialPort == null || !serialPort.isOpen()){
System.out.println("COM口未打开");
logger.info("COM口未打开");
return -2;
}
int result = serialPort.writeBytes(data,data.length);//将字节数组全部写入串口
if(result != -1){
System.out.println("COM口已成功写入数据");
logger.info("COM口已成功写入数据");
}else{
System.out.println("COM口写数据失败");
logger.error("COM口写数据失败");
}
return result;
}
private String readComm(SerialPort serialPort) {
if (serialPort == null || !serialPort.isOpen()) {
System.out.println("COM口未打开");
logger.error("COM口未打开");
return null;
}
String readData = "";
......@@ -93,7 +92,7 @@ public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exceptionCaught! cause:" + cause.toString());
logger.error("exceptionCaught! cause:" + cause.toString());
ctx.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds" debug="false">
<contextName>GnssServer</contextName>
<property name="log.charset" value="ANSI" />
<property name="log.pattern" value="%contextName- %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %msg%n" />
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
              <fileNamePattern>GnssServerLog.%d{yyyy-MM-dd}.log</fileNamePattern>
              <maxHistory>30</maxHistory>
            </rollingPolicy>
            <encoder>
              <pattern>%date [%thread] %-5level %logger{35} - %msg%n</pattern>
            </encoder>
</appender>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
<charset>${log.charset}</charset>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console" />
<appender-ref ref="FILE" />
</root>
</configuration>
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