Prechádzať zdrojové kódy

tablestoreApi查询表格存储java版本,SchoolRFIDTcp 谷米gps模拟数据发送

ok 5 rokov pred
rodič
commit
07f9e4aed8
100 zmenil súbory, kde vykonal 1724 pridanie a 0 odobranie
  1. 10 0
      .gitignore
  2. 8 0
      SchoolRFIDTcp/.classpath
  3. 17 0
      SchoolRFIDTcp/.project
  4. 2 0
      SchoolRFIDTcp/.settings/org.eclipse.core.resources.prefs
  5. 11 0
      SchoolRFIDTcp/.settings/org.eclipse.jdt.core.prefs
  6. BIN
      SchoolRFIDTcp/bin/Cls2.class
  7. BIN
      SchoolRFIDTcp/bin/Inner.class
  8. BIN
      SchoolRFIDTcp/bin/ListTest$1.class
  9. BIN
      SchoolRFIDTcp/bin/ListTest.class
  10. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/ByteToIntegerDecoder.class
  11. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient$1.class
  12. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient$2.class
  13. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient.class
  14. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServer$1.class
  15. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServer.class
  16. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServerHandler.class
  17. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClient$1.class
  18. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClient.class
  19. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClientHandler.class
  20. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServer$1.class
  21. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServer.class
  22. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServerHandler.class
  23. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClient$1.class
  24. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClient.class
  25. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClientIntHandler.class
  26. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServer$1.class
  27. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServer.class
  28. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServerInHandler.class
  29. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HttpHandler.class
  30. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HttpServer$1.class
  31. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/HttpServer.class
  32. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/IntegerToByteEncoder.class
  33. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/MysqlTest$1.class
  34. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/MysqlTest.class
  35. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/TimeClientHandler2.class
  36. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsData.class
  37. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsDecoder$State.class
  38. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsDecoder.class
  39. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsEncoder.class
  40. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsHeader.class
  41. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsHeartBeat.class
  42. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsLogin.class
  43. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequest.class
  44. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequestAbstruct.class
  45. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequestInterface2.class
  46. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient$1.class
  47. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient$2.class
  48. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient.class
  49. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/SocketClient$WriteThread.class
  50. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/SocketClient.class
  51. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/TimeClientHandler.class
  52. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/Utils.class
  53. BIN
      SchoolRFIDTcp/bin/com/renlianiot/demo/gps/gr.class
  54. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Card.class
  55. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/CardInfo.class
  56. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/CardPool.class
  57. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Decoder.class
  58. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/EnumAttendance.class
  59. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/EnumRFIDStatus.class
  60. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Handler.class
  61. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/PoolToken.class
  62. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Rfid$RfidBody.class
  63. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Rfid.class
  64. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/RfidDecoder$State.class
  65. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/RfidDecoder.class
  66. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/RfidEncoder.class
  67. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/RfidHandler.class
  68. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/School$1.class
  69. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/School$2.class
  70. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/School.class
  71. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Station.class
  72. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Test$1.class
  73. BIN
      SchoolRFIDTcp/bin/com/renlianiot/school/Test.class
  74. BIN
      SchoolRFIDTcp/mysql-connector-java-5.1.39-bin.jar
  75. BIN
      SchoolRFIDTcp/netty-all-4.1.32.Final.jar
  76. 107 0
      SchoolRFIDTcp/src/ListTest.java
  77. 24 0
      SchoolRFIDTcp/src/com/renlianiot/demo/ByteToIntegerDecoder.java
  78. 233 0
      SchoolRFIDTcp/src/com/renlianiot/demo/CopyOfMultiClient.java
  79. 62 0
      SchoolRFIDTcp/src/com/renlianiot/demo/DiscardServer.java
  80. 64 0
      SchoolRFIDTcp/src/com/renlianiot/demo/DiscardServerHandler.java
  81. 61 0
      SchoolRFIDTcp/src/com/renlianiot/demo/EchoClient.java
  82. 32 0
      SchoolRFIDTcp/src/com/renlianiot/demo/EchoClientHandler.java
  83. 56 0
      SchoolRFIDTcp/src/com/renlianiot/demo/EchoServer.java
  84. 36 0
      SchoolRFIDTcp/src/com/renlianiot/demo/EchoServerHandler.java
  85. 44 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HelloClient.java
  86. 49 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HelloClientIntHandler.java
  87. 52 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HelloServer.java
  88. 55 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HelloServerInHandler.java
  89. 46 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HttpHandler.java
  90. 54 0
      SchoolRFIDTcp/src/com/renlianiot/demo/HttpServer.java
  91. 15 0
      SchoolRFIDTcp/src/com/renlianiot/demo/IntegerToByteEncoder.java
  92. 378 0
      SchoolRFIDTcp/src/com/renlianiot/demo/MysqlTest.java
  93. 82 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsData.java
  94. 71 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsDecoder.java
  95. 55 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsEncoder.java
  96. 32 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsHeader.java
  97. 24 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsHeartBeat.java
  98. 28 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsLogin.java
  99. 16 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsRequest.java
  100. 0 0
      SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsRequestAbstruct.java

+ 10 - 0
.gitignore

@@ -7,3 +7,13 @@
 # Linux trash folder which might appear on any partition or disk
 .Trash-*
 
+
+.metadata/*
+console_test/*
+liehuGps/*
+liehuTcp/*
+ntp/*
+RemoteSystemsTempFiles/*
+Servers/*
+sms
+tablestore/*

+ 8 - 0
SchoolRFIDTcp/.classpath

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
+	<classpathentry kind="lib" path="E:/java_workspace/SchoolRFIDTcp/mysql-connector-java-5.1.39-bin.jar"/>
+	<classpathentry kind="lib" path="E:/java_workspace/SchoolRFIDTcp/netty-all-4.1.32.Final.jar"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

+ 17 - 0
SchoolRFIDTcp/.project

@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>SchoolRFIDTcp</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>

+ 2 - 0
SchoolRFIDTcp/.settings/org.eclipse.core.resources.prefs

@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+encoding//src/com/renlianiot/school/School.java=UTF-8

+ 11 - 0
SchoolRFIDTcp/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,11 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.8

BIN
SchoolRFIDTcp/bin/Cls2.class


BIN
SchoolRFIDTcp/bin/Inner.class


BIN
SchoolRFIDTcp/bin/ListTest$1.class


BIN
SchoolRFIDTcp/bin/ListTest.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/ByteToIntegerDecoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient$2.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/CopyOfMultiClient.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServer$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServer.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/DiscardServerHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClient$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClient.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoClientHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServer$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServer.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/EchoServerHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClient$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClient.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloClientIntHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServer$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServer.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HelloServerInHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HttpHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HttpServer$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/HttpServer.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/IntegerToByteEncoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/MysqlTest$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/MysqlTest.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/TimeClientHandler2.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsData.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsDecoder$State.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsDecoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsEncoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsHeader.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsHeartBeat.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsLogin.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequest.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequestAbstruct.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/GpsRequestInterface2.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient$2.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/MultiClient.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/SocketClient$WriteThread.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/SocketClient.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/TimeClientHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/Utils.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/demo/gps/gr.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Card.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/CardInfo.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/CardPool.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Decoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/EnumAttendance.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/EnumRFIDStatus.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Handler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/PoolToken.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Rfid$RfidBody.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Rfid.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/RfidDecoder$State.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/RfidDecoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/RfidEncoder.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/RfidHandler.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/School$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/School$2.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/School.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Station.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Test$1.class


BIN
SchoolRFIDTcp/bin/com/renlianiot/school/Test.class


BIN
SchoolRFIDTcp/mysql-connector-java-5.1.39-bin.jar


BIN
SchoolRFIDTcp/netty-all-4.1.32.Final.jar


+ 107 - 0
SchoolRFIDTcp/src/ListTest.java

@@ -0,0 +1,107 @@
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+
+public class ListTest {
+
+	static ArrayList<Cls2> list = new ArrayList<Cls2>();
+	static void test2() {
+		final ArrayList<Cls2> list2 = (ArrayList<Cls2>) list.clone();
+		threadPool.execute(() -> {
+			
+			try {
+				Thread.sleep(5000);
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			
+			System.out.println("threadid1:" + Thread.currentThread().getId() + " " + list2.size());
+//			threadPool.shutdown();
+			
+		});
+	}
+	private static ExecutorService threadPool = Executors.newFixedThreadPool(1);
+	public static void main(String[] args) {
+		Cls2 inner = new Cls2() {
+			public String st = "1111";
+			public int st2 = 2222;
+			public int st22 = 2222;
+		};
+		try {
+
+		       Class userCla = (Class) inner.getClass();
+System.out.println(userCla.getDeclaredFields().length+" len");
+
+		       if (null == userCla.getDeclaredField("st22"))
+		       System.out.println("null");
+int j = 100;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		
+		list.add(new Cls2());
+		test2();
+		
+		list.add(inner);
+//		test2();
+		
+		
+//		ArrayList<Cls2> list3 = (ArrayList<Cls2>) list.clone();
+//		threadPool.execute(() -> {
+//			
+//			try {
+//				Thread.sleep(5000);
+//			} catch (Exception e) {
+//				e.printStackTrace();
+//			}
+//			
+//			System.out.println("threadid2:" + Thread.currentThread().getId() + " " + list3.size());
+//			
+//			
+//		});
+		System.out.println("OK");
+		list.clear();
+		if (true) {
+			return;
+		}
+		
+
+		
+		
+		
+		
+		
+
+		
+		
+		if (true) {
+			return;
+		}
+		list.add(new Cls2());
+		clo();
+		list.clear();
+//		System.out.println("main:" + list.get(0).str);
+		System.out.println("main:" + list.size());
+		
+		
+	}
+	static void clo() {
+		ArrayList<Cls2> list2 = (ArrayList<Cls2>) list.clone();
+		list2.add(new Cls2());
+		list2.get(0).str = "11111";
+		System.out.println(list2.get(0).str);
+		System.out.println(list2.size());
+	}
+
+}
+class Inner{
+	
+}
+class Cls2 {
+	public Cls2() {
+		str = "cls";
+	}
+	public String str;
+}

+ 24 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/ByteToIntegerDecoder.java

@@ -0,0 +1,24 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+
+import java.util.List;
+
+/**
+ * 把字节转换为int
+ * 继承抽象类ByteToMessageDecoder实现解码器
+ */
+public class ByteToIntegerDecoder extends ByteToMessageDecoder {
+
+    @Override
+    public void decode(ChannelHandlerContext ctx, ByteBuf in,
+                       List<Object> out) throws Exception {
+        if (in.readableBytes() >= 4) {  // Check if there are at least 4 bytes readable
+            int n = in.readInt();
+            System.err.println("ByteToIntegerDecoder decode msg is " + n);
+            out.add(n);      //Read integer from inbound ByteBuf, add to the List of decodec messages
+        }
+    }
+}

+ 233 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/CopyOfMultiClient.java

@@ -0,0 +1,233 @@
+package com.renlianiot.demo;
+
+import java.net.InetSocketAddress;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.Date;
+import java.text.SimpleDateFormat;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.handler.codec.LineBasedFrameDecoder;
+import io.netty.handler.codec.string.StringDecoder;
+import io.netty.util.CharsetUtil;
+import io.netty.util.concurrent.ScheduledFuture;
+
+ //https://blog.csdn.net/everyok/article/details/84852398
+public class CopyOfMultiClient {
+ 
+    //服务端的IP
+    private static final String SERVER_HOST = "192.168.1.187";
+ 
+    static final int BEGIN_PORT = 10201;
+    static final int N_PORT = 1;
+ 
+    public static void main(String[] args) {
+        new CopyOfMultiClient().start(BEGIN_PORT, N_PORT);
+    }
+ 
+    public void start(final int beginPort, int nPort) {
+        System.out.println("client starting....");
+        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
+        final Bootstrap bootstrap = new Bootstrap();
+        bootstrap.group(eventLoopGroup);
+        bootstrap.channel(NioSocketChannel.class);
+        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
+        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
+            @Override
+            protected void initChannel(SocketChannel ch) {
+            	 ChannelPipeline pipeline = ch.pipeline(); 
+                 
+                 // LineBasedFrameDecoder按行分割消息 
+                 pipeline.addLast(
+                		 new LineBasedFrameDecoder(80),
+                		 new StringDecoder(CharsetUtil.UTF_8),
+                		 new TimeClientHandler2()
+                		 );
+            }
+        });
+ 
+        int index = 0;
+        int port;
+        //从10000的端口开始,按端口递增的方式进行连接
+        ChannelFuture channelFuture = null;
+        while (!Thread.interrupted()) {
+        	
+
+        	
+            port = beginPort;// + index;
+            try {
+                channelFuture = bootstrap.connect(SERVER_HOST, port).sync();
+                channelFuture.addListener((ChannelFutureListener) future -> {
+                    if (!future.isSuccess()) {
+                        System.out.println("connect failed, exit!");
+                        System.exit(0);
+                    } else {
+                    	//System.out.println("connect OK");
+                    	
+                    }
+                });
+                channelFuture.get();
+                
+                
+                //单个定时任务
+//                Channel channel = channelFuture.channel();
+//                channelFuture.channel().eventLoop().scheduleAtFixedRate(
+//                        () -> {
+//                            try {
+//                            	channel.writeAndFlush(Unpooled.copiedBuffer(new SimpleDateFormat("HH:mm:ss").format(new Date())
+//                                    		+" "+ channel.hashCode() + " heartbeat\n", //2
+//                                	        CharsetUtil.UTF_8));
+//                            } catch (Exception e) {
+//                                e.printStackTrace();
+//                            }
+//
+//                        }, 10,  10, TimeUnit.SECONDS);//60 * 5秒周期
+                
+                
+
+                
+               // channelFuture.channel().closeFuture().sync();
+            } catch (Exception e) {
+            }
+ 
+            if (++index == nPort) {
+                index = 0;
+                if (index % 1000 == 0) {
+	            	try {
+	    				Thread.sleep(10);
+	    			} catch (InterruptedException e1) {
+	    				// TODO Auto-generated catch block
+	    				e1.printStackTrace();
+	    			}
+                }
+                break;
+            }
+        }
+
+        //定时下发时间给所有客户端
+//        ScheduledFuture<?> future =  channelFuture.channel().eventLoop().scheduleAtFixedRate(
+//                () -> {
+//                    try {
+//                    	System.out.println("count:"+TimeClientHandler.ChannelMap.size());
+//                        for (Map.Entry<String, Channel> entry : TimeClientHandler.ChannelMap.entrySet()) {
+//                            Channel channel = entry.getValue();
+//                            channel.writeAndFlush(Unpooled.copiedBuffer(new SimpleDateFormat("HH:mm:ss").format(new Date())
+//                            		+" "+ channel.hashCode() + " heartbeat\n", //2
+//                        	        CharsetUtil.UTF_8));
+//                        }
+//                    } catch (Exception e) {
+//                        e.printStackTrace();
+//                    }
+//
+//                }, 10,  10, TimeUnit.SECONDS);//60 * 5秒周期
+
+        //线程定时下发所有
+        new Thread(new Runnable() {
+			
+			@Override
+			public void run() {
+				
+				while (true) {
+						try {
+							Thread.sleep(10 * 1000);
+						} catch (InterruptedException e1) {
+							e1.printStackTrace();
+						}
+						System.out.println("count:"+TimeClientHandler2.ChannelMap.size());
+		              try {
+		            	System.out.println("count:"+TimeClientHandler2.ChannelMap.size());
+		                for (Map.Entry<String, Channel> entry : TimeClientHandler2.ChannelMap.entrySet()) {
+		                    Channel channel = entry.getValue();
+		                    channel.writeAndFlush(Unpooled.copiedBuffer(new SimpleDateFormat("HH:mm:ss").format(new Date())
+		                    		+" "+ channel.hashCode() + " heartbeat\n", //2
+		                	        CharsetUtil.UTF_8));
+		                }
+		            } catch (Exception e) {
+		                e.printStackTrace();
+		            }
+				}
+				
+			}
+		}).start();
+        
+        
+        
+        
+        
+        
+//        future.cancel(false);
+
+       
+    }
+}
+
+class TimeClientHandler2 extends ChannelInboundHandlerAdapter {
+	public static ConcurrentHashMap<String, Channel> ChannelMap = new ConcurrentHashMap<>();
+    public TimeClientHandler2() {
+    }
+	@Override
+	public void channelRegistered(ChannelHandlerContext ctx)
+	  throws Exception
+	{
+		
+
+	    
+	}
+	@Override
+	public void channelUnregistered(ChannelHandlerContext ctx)
+	  throws Exception
+	{
+
+	}
+ 
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+		String ip = Thread.currentThread().getId() +"";
+		int hcode = ctx.channel().hashCode();
+		ctx.channel().writeAndFlush(hcode + " login\n");
+		ChannelMap.put( "@" + hcode, ctx.channel());
+	   // System.out.println("channelRegistered " + ip + "@" + hcode);
+    	ctx.writeAndFlush( Unpooled.copiedBuffer(hcode + " login\n", //2
+    	        CharsetUtil.UTF_8));
+    }
+    
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+    	InetSocketAddress socketAddr = (InetSocketAddress )(ctx.channel().localAddress());
+    	String socketIP = socketAddr .getHostString();
+    	int socketORTP = socketAddr.getPort();
+
+		ChannelMap.remove( "@" + ctx.channel().hashCode());
+		System.out.println(socketORTP +" channelUnregistered " + "@" + ctx.channel().hashCode());
+    }
+    
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        String body = (String) msg;
+//        System.out.println(
+//                body
+//        );
+    }
+ 
+ 
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+        cause.printStackTrace();
+        ctx.close();
+    }
+}

+ 62 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/DiscardServer.java

@@ -0,0 +1,62 @@
+package com.renlianiot.demo;
+
+import io.netty.bootstrap.ServerBootstrap;
+
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+
+/**
+ * Discards any incoming data.
+ */
+
+public class DiscardServer {
+	private int port;
+
+    public DiscardServer(int port) {
+        this.port = port;
+    }
+
+    public void run() throws Exception {
+        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
+        EventLoopGroup workerGroup = new NioEventLoopGroup();
+        try {
+            ServerBootstrap b = new ServerBootstrap(); // (2)
+            b.group(bossGroup, workerGroup)
+             .channel(NioServerSocketChannel.class) // (3)
+             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
+                 @Override
+                 public void initChannel(SocketChannel ch) throws Exception {
+                     ch.pipeline().addLast(new DiscardServerHandler());
+                 }
+             })
+             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
+             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
+
+            // Bind and start to accept incoming connections.
+            ChannelFuture f = b.bind(port).sync(); // (7)
+
+            // Wait until the server socket is closed.
+            // In this example, this does not happen, but you can do that to gracefully
+            // shut down your server.
+            f.channel().closeFuture().sync();
+        } finally {
+            workerGroup.shutdownGracefully();
+            bossGroup.shutdownGracefully();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        int port;
+        if (args.length > 0) {
+            port = Integer.parseInt(args[0]);
+        } else {
+            port = 8080;
+        }
+        new DiscardServer(port).run();
+    }
+}

+ 64 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/DiscardServerHandler.java

@@ -0,0 +1,64 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.util.ReferenceCountUtil;
+
+public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
+        // 以静默方式丢弃接收的数据
+//        ((ByteBuf) msg).release(); // (3)
+    	
+    	 ByteBuf in = (ByteBuf) msg;
+    	    try {
+    	        while (in.isReadable()) { // (1)
+    	            System.out.print((char) in.readByte());
+    	            System.out.flush();
+    	        }
+    	    } finally {
+    	        ReferenceCountUtil.release(msg); // (2)
+    	    }
+    	    // 或者直接打印
+    	    System.out.println("Yes, A new client in = " + ctx.name());
+    	    
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
+        // 出现异常时关闭连接。
+        cause.printStackTrace();
+        ctx.close();
+    }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 61 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/EchoClient.java

@@ -0,0 +1,61 @@
+package com.renlianiot.demo;
+
+import java.net.InetSocketAddress;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+
+public class EchoClient {
+
+    private final String host;
+    private final int port;
+
+    public EchoClient(String host, int port) {
+        this.host = host;
+        this.port = port;
+    }
+
+    public void start() throws Exception {
+        EventLoopGroup group = new NioEventLoopGroup();
+        try {
+            Bootstrap b = new Bootstrap();                //1
+            b.group(group)                                //2
+             .channel(NioSocketChannel.class)            //3
+             .remoteAddress(new InetSocketAddress(host, port))    //4
+             .handler(new ChannelInitializer<SocketChannel>() {    //5
+                 @Override
+                 public void initChannel(SocketChannel ch) 
+                     throws Exception {
+                     ch.pipeline().addLast(
+                             new EchoClientHandler());
+                 }
+             });
+
+            ChannelFuture f = b.connect().sync();        //6
+
+            f.channel().closeFuture().sync();            //7
+        } finally {
+            group.shutdownGracefully().sync();            //8
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+//        if (args.length != 2) {
+//            System.err.println(
+//                    "Usage: " + EchoClient.class.getSimpleName() +
+//                    " <host> <port>");
+//            return;
+//        }
+//
+//        final String host = args[0];
+//        final int port = Integer.parseInt(args[1]);
+
+       // new EchoClient("127.0.0.1", 8800).start();
+        new EchoClient("192.168.1.187", 10200).start();
+    }
+}

+ 32 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/EchoClientHandler.java

@@ -0,0 +1,32 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.util.CharsetUtil;
+
+@Sharable                                //1
+public class EchoClientHandler extends
+        SimpleChannelInboundHandler<ByteBuf> {
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) {
+        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!\n", //2
+        CharsetUtil.UTF_8));
+    }
+
+    @Override
+    public void channelRead0(ChannelHandlerContext ctx,
+        ByteBuf in) {
+        System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));    //3
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx,
+        Throwable cause) {                    //4
+        cause.printStackTrace();
+        ctx.close();
+    }
+}

+ 56 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/EchoServer.java

@@ -0,0 +1,56 @@
+package com.renlianiot.demo;
+
+import java.net.InetSocketAddress;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.ByteToMessageCodec;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.handler.codec.string.StringDecoder;
+import io.netty.handler.codec.string.StringEncoder;
+
+public class EchoServer {
+	private final int port;
+
+    public EchoServer(int port) {
+        this.port = port;
+    }
+        public static void main(String[] args) throws Exception {
+        if (args.length != 1) {
+            System.err.println(
+                    "Usage: " + EchoServer.class.getSimpleName() +
+                    " <port>");
+            return;
+        }
+        int port = Integer.parseInt(args[0]);        //1
+        new EchoServer(port).start();                //2
+    }
+
+    public void start() throws Exception {
+        NioEventLoopGroup group = new NioEventLoopGroup(); //3
+        try {
+            ServerBootstrap b = new ServerBootstrap();
+            b.group(group)                                //4
+             .channel(NioServerSocketChannel.class)        //5
+             .localAddress(new InetSocketAddress(port))    //6
+             .childHandler(new ChannelInitializer<SocketChannel>() { //7
+                 @Override
+                 public void initChannel(SocketChannel ch) 
+                     throws Exception {
+                     ch.pipeline().addLast(
+                             new EchoServerHandler());
+                 }
+             });
+
+            ChannelFuture f = b.bind().sync();            //8
+            System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
+            f.channel().closeFuture().sync();            //9
+        } finally {
+            group.shutdownGracefully().sync();            //10
+        }
+    }
+}

+ 36 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/EchoServerHandler.java

@@ -0,0 +1,36 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.util.CharsetUtil;
+
+public class EchoServerHandler extends ChannelInboundHandlerAdapter {
+
+	@Override
+	public void channelRead(ChannelHandlerContext ctx, Object msg) {
+		ByteBuf in = (ByteBuf) msg;
+		System.out
+				.println("Server received: " + in.toString(CharsetUtil.UTF_8)); // 2
+//		ctx.writeAndFlush(in); // 3
+		
+		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.US_ASCII));
+	}
+
+	@Override
+	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+		System.out
+		.println("Server channelReadComplete"); // 2
+		
+//		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)// 4
+//				.addListener(ChannelFutureListener.CLOSE);
+	}
+
+	@Override
+	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+		cause.printStackTrace(); // 5
+		ctx.close(); // 6
+	}
+}

+ 44 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HelloClient.java

@@ -0,0 +1,44 @@
+package com.renlianiot.demo;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+
+public class HelloClient {
+
+    public void connect(String host, int port) throws Exception {
+
+        EventLoopGroup workerGroup = new NioEventLoopGroup();
+
+        try {
+            Bootstrap b = new Bootstrap();
+            b.group(workerGroup);
+            b.channel(NioSocketChannel.class);
+            b.option(ChannelOption.AUTO_READ, true);
+            b.handler(new ChannelInitializer<SocketChannel>() {
+                @Override
+                public void initChannel(SocketChannel ch) throws Exception {
+                    ch.pipeline().addLast(
+                            new IntegerToByteEncoder(),
+                            new ByteToIntegerDecoder(),
+                            new HelloClientIntHandler());
+                }
+            });
+            ChannelFuture f = b.connect(host, port).sync();
+            f.channel().closeFuture().sync();
+        } finally {
+            workerGroup.shutdownGracefully();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        HelloClient client = new HelloClient();
+        //client.connect("127.0.0.1", 12345);
+        client.connect("192.168.1.187", 10200);
+    }
+}

+ 49 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HelloClientIntHandler.java

@@ -0,0 +1,49 @@
+package com.renlianiot.demo;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+
+
+//InboundHandler类型
+public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
+
+    @Override
+    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("==============channel--register==============");
+    }
+
+    @Override
+    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("==============channel--unregistered==============");
+    }
+
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("==============channel--inactive==============");
+    }
+
+    // 连接成功后,向server发送消息
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("==============channel--active==============");
+        System.out.println("向服务器端写入1991数字");
+        ctx.write(1991);
+        ctx.flush();
+    }
+
+    // 接收server端的消息,并打印出来
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        System.out.println("==============channel--read==============");
+        System.out.println("the msg type is " + msg.getClass().getName());
+
+        Integer result = (Integer) msg;
+        System.out.println("接收到服务器数据整形是" + result);
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+        cause.printStackTrace();
+        ctx.close();
+    }
+}

+ 52 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HelloServer.java

@@ -0,0 +1,52 @@
+package com.renlianiot.demo;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+
+/**
+ * 主要思路:
+ * 实现了一个编码器IntegerToByteEncoder和一个解码器ByteToIntegerDecoder
+ * 客户端直接发送一个数字
+ * 服务器端接收后向客户端发送一个数字
+ * 在这过程中可以看到解码器和编码器所起的作用
+ */
+public class HelloServer {
+    public void start(int port) throws Exception {
+        EventLoopGroup bossGroup = new NioEventLoopGroup();
+        EventLoopGroup workerGroup = new NioEventLoopGroup();
+        try {
+            ServerBootstrap b = new ServerBootstrap();
+            b.group(bossGroup, workerGroup)
+                    .channel(NioServerSocketChannel.class)
+                    .option(ChannelOption.SO_BACKLOG, 128)
+                    .childHandler(new ChannelInitializer<SocketChannel>() {
+                        @Override
+                        public void initChannel(SocketChannel ch) throws Exception {
+                            // 注册handler
+                            ch.pipeline().addLast(
+                                    new IntegerToByteEncoder(),
+                                    new ByteToIntegerDecoder(),
+                                    new HelloServerInHandler());
+                        }
+                    });
+
+            ChannelFuture f = b.bind(port).sync();
+            f.channel().closeFuture().sync();
+
+        } finally {
+            workerGroup.shutdownGracefully();
+            bossGroup.shutdownGracefully();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        HelloServer server = new HelloServer();
+        server.start(12345);
+    }
+}

+ 55 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HelloServerInHandler.java

@@ -0,0 +1,55 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+
+// 该handler是InboundHandler类型
+public class HelloServerInHandler extends ChannelInboundHandlerAdapter {
+//    @Override
+//    public boolean isSharable() {
+//        System.out.println("==============handler-sharable==============");
+//        return super.isSharable();
+//    }
+//
+//    @Override
+//    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
+//        System.out.println("==============channel-register==============");
+//    }
+//
+//    @Override
+//    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+//        System.out.println("==============channel-unregister==============");
+//    }
+//
+//    @Override
+//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+//        System.out.println("==============channel-active==============");
+//
+//    }
+//
+//    @Override
+//    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+//        System.out.println("==============channel-inactive==============");
+//    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+
+        System.out.println("==============channel-read==============");
+        System.out.println("the msg type is " + msg.getClass().getName());
+        Integer integer = (Integer) msg;
+        System.out.println("服务器端接收到的客户端的数字是" + integer);
+
+
+        System.out.println("服务器向客户端写入整型数字2000");
+        ctx.writeAndFlush(2000);
+//        ctx.close();
+    }
+
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("==============channel-read-complete==============");
+        ctx.flush();
+    }
+}

+ 46 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HttpHandler.java

@@ -0,0 +1,46 @@
+package com.renlianiot.demo;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.codec.http.*;
+import io.netty.util.AsciiString;
+
+
+public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> { // 1
+
+    private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {   //1
+        System.out.println(
+                "Client " + ctx.channel().remoteAddress() + " connected");
+    }
+    @Override
+    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
+        System.out.println("class:" + msg.getClass().getName());
+        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
+                HttpResponseStatus.OK,
+                Unpooled.wrappedBuffer("test".getBytes())); // 2
+
+        HttpHeaders heads = response.headers();
+        heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
+        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 3
+        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
+
+        ctx.write(response);
+    }
+
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+        System.out.println("channelReadComplete");
+        super.channelReadComplete(ctx);
+        ctx.flush(); // 4
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+        System.out.println("exceptionCaught");
+        if(null != cause) cause.printStackTrace();
+        if(null != ctx) ctx.close();
+    }
+}

+ 54 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/HttpServer.java

@@ -0,0 +1,54 @@
+package com.renlianiot.demo;
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.http.HttpObjectAggregator;
+import io.netty.handler.codec.http.HttpRequestDecoder;
+import io.netty.handler.codec.http.HttpResponseEncoder;
+
+
+
+public class HttpServer {
+	private final int port;
+
+    public HttpServer(int port) {
+        this.port = port;
+    }
+
+    public static void main(String[] args) throws Exception {
+//        if (args.length != 1) {
+//            System.err.println(
+//                    "Usage: " + HttpServer.class.getSimpleName() +
+//                            " <port>");
+//            return;
+//        }
+       // int port = Integer.parseInt(args[0]);
+        new HttpServer(88).start();
+    }
+
+    public void start() throws Exception {
+        ServerBootstrap b = new ServerBootstrap();
+        NioEventLoopGroup group = new NioEventLoopGroup();
+        b.group(group)
+                .channel(NioServerSocketChannel.class)
+                .childHandler(new ChannelInitializer<SocketChannel>() {
+                    @Override
+                    public void initChannel(SocketChannel ch)
+                            throws Exception {
+                        System.out.println("initChannel ch:" + ch);
+                        ch.pipeline()
+                                .addLast("decoder", new HttpRequestDecoder())   // 1
+                                .addLast("encoder", new HttpResponseEncoder())  // 2
+                                .addLast("aggregator", new HttpObjectAggregator(512 * 1024))    // 3
+                                .addLast("handler", new HttpHandler());        // 4
+                    }
+                })
+                .option(ChannelOption.SO_BACKLOG, 128) // determining the number of connections queued
+                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
+
+        b.bind(port).sync();
+    }
+}

+ 15 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/IntegerToByteEncoder.java

@@ -0,0 +1,15 @@
+package com.renlianiot.demo;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+public class IntegerToByteEncoder extends MessageToByteEncoder<Integer> {
+    @Override
+    public void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out)
+            throws Exception {
+        System.err.println("IntegerToByteEncoder encode msg is " + msg);
+        out.writeInt(msg);
+//        out.writeBytes("hello".getBytes());
+    }
+}

+ 378 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/MysqlTest.java

@@ -0,0 +1,378 @@
+package com.renlianiot.demo;
+
+import io.netty.handler.codec.mqtt.MqttMessageBuilders.PublishBuilder;
+
+import java.io.ObjectInputStream.GetField;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Date;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+
+import com.mysql.jdbc.Connection;
+import com.mysql.jdbc.PreparedStatement;
+import com.mysql.jdbc.Statement;
+
+public class MysqlTest {
+
+	static int startDeviceId = 0;
+	static String did2 = null;
+
+	public static String getDeviceId() {
+		startDeviceId++;
+
+		if (did2 != null && startDeviceId < 11) {
+			return did2;
+		}
+		startDeviceId = 0;
+
+		did2 = String.format("%020d", (int) (100000 + Math.random()
+				* (200000 - 100000 + 1)));
+		return did2;
+
+		// return String.format("%020d", (int) (1 + Math.random()
+		// * (100000 - 1 + 1)));
+	}
+
+	public static double getLong() {
+		double min = 0.0001;// 最小值
+		double max = 117;// 总和
+		int scl = 6;// 小数最大位数
+		int pow = (int) Math.pow(10, scl);// 指定小数位
+		double one = Math.floor((Math.random() * (max - min) + min) * pow)
+				/ pow;
+		return one;
+	}
+
+	public static double getLatit() {
+		double min = 0.0001;// 最小值
+		double max = 40;// 总和
+		int scl = 6;// 小数最大位数
+		int pow = (int) Math.pow(10, scl);// 指定小数位
+		double one = Math.floor((Math.random() * (max - min) + min) * pow)
+				/ pow;
+		return one;
+	}
+
+	public static int getSpeed() {
+		return (int) (1 + Math.random() * (32367 - 1 + 1));
+	}
+
+	public static int getDirection() {
+		return (int) (1 + Math.random() * (32367 - 1 + 1));
+	}
+
+	public static int getStatus() {
+		return (int) (1 + Math.random() * (127 - 1 + 1));
+	}
+
+	public static int getSatelliteCount() {
+		return (int) (1 + Math.random() * (127 - 1 + 1));
+	}
+
+	// 生成随机数字和字母,
+	public static String getStringRandom(int length) {
+
+		String val = "";
+		Random random = new Random();
+
+		// 参数length,表示生成几位随机数
+		for (int i = 0; i < length; i++) {
+
+			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
+			// 输出字母还是数字
+			if ("char".equalsIgnoreCase(charOrNum)) {
+				// 输出是大写字母还是小写字母
+				int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
+				val += (char) (random.nextInt(26) + temp);
+			} else if ("num".equalsIgnoreCase(charOrNum)) {
+				val += String.valueOf(random.nextInt(10));
+			}
+		}
+		return val;
+	}
+
+	public static String getLBS() {
+		return getStringRandom(8);
+	}
+
+	public static void execTransSql0(Connection connTrans) {
+		PreparedStatement psTrans = null;
+		// 加载驱动类
+		try {
+			connTrans.setAutoCommit(false); // JDBC中默认是true,我们改成false,然后在后面手动提交
+
+			// 拼成一条sql语句发送
+			String sql = String
+					.format("insert into gps_location_myisam(`DeviceId`,`DeviceTime`,"
+							+ "`Longitude`,`Latitude`,`Speed`,`Direction`,`Status`,`SatelliteCount`,`LBS`)values");
+
+			StringBuffer sb = new StringBuffer();
+			sb.append(sql);
+			for (int i = 0; i < 3000; i++) {
+				sb.append(String.format("('%s',%d,%f,%f,%d,%d,%d,%d,'%s'),",
+						getDeviceId(), System.currentTimeMillis() / 1000,
+						getLong(), getLatit(), getSpeed(), getDirection(),
+						getStatus(), getSatelliteCount(), getLBS()));
+
+				// System.out.println("build time: "+(System.currentTimeMillis()
+				// - startTime) + "ms");
+				// startTime = System.currentTimeMillis(); //获取开始时间
+
+			}
+			sql += sb.toString();
+			// System.out.println(sql);
+			psTrans = (PreparedStatement) connTrans.prepareStatement(sb
+					.toString().substring(0, sb.length() - 1));
+			psTrans.execute();
+			System.out.println("exec sql OK");
+			// Thread.sleep(5000000);
+			connTrans.commit();// 提交事务
+		} catch (Exception e) {
+			try {
+				connTrans.rollback();
+			} catch (SQLException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			}// 某一条数据添加失败时,回滚
+			e.printStackTrace();
+		} finally {
+			try {
+				if (psTrans != null) {
+					psTrans.close();
+				}
+			} catch (SQLException e) {
+				e.printStackTrace();
+			}
+
+		}
+	}
+
+	public static void execTransSql() {
+		Connection connTrans = null;
+		try {
+
+			Class.forName("com.mysql.jdbc.Driver");
+
+			connTrans = (Connection) DriverManager
+					.getConnection(
+							"jdbc:mysql://192.168.1.187:3306/gps?characterEncoding=UTF-8",
+							"root", "jrtk.net");
+			for (int j = 0; j < 20; j++) {
+				execTransSql0(connTrans);
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (connTrans != null) {
+					connTrans.close();
+				}
+			} catch (SQLException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public static void execSql(int id) {
+		try {
+			// System.out.println(getLong());
+			// if (true){
+			// return;
+			// }
+			// 1.加载数据访问驱动
+			Class.forName("com.mysql.jdbc.Driver");
+			// 2.连接到数据"库"上去
+			// long startTime = System.currentTimeMillis(); //获取开始时间
+			Connection conn = (Connection) DriverManager
+					.getConnection(
+							"jdbc:mysql://192.168.1.187:3306/gps?characterEncoding=UTF-8",
+							"root", "jrtk.net");
+
+			// Connection conn = (Connection) DriverManager
+			// .getConnection(
+			// "jdbc:mysql://rm-hp3gk936r4d971vi19o.mysql.huhehaote.rds.aliyuncs.com:3306/dev_fd_gps?characterEncoding=UTF-8",
+			// "jyzl", "A295c237ff2f407c");
+
+			// System.out.println("connect time: "+(System.currentTimeMillis() -
+			// startTime) + "ms");
+			// 3.构建SQL命令
+			// startTime = System.currentTimeMillis(); //获取开始时间
+			Statement state = (Statement) conn.createStatement();
+
+			// 一条条发送
+			// for (int i = 0; i < 1000; i++) {
+			// String sql = String
+			// .format("insert into gps_location_innodb(`DeviceId`,`DeviceTime`,"
+			// +
+			// "`Longitude`,`Latitude`,`Speed`,`Direction`,`Status`,`SatelliteCount`,`LBS`) "
+			// + " values('%s',%d,%f,%f,%d,%d,%d,%d,'%s')",
+			// getDeviceId(),
+			// System.currentTimeMillis() / 1000, getLong(),
+			// getLatit(), getSpeed(), getDirection(),
+			// getStatus(), getSatelliteCount(), getLBS());
+			// // System.out.println(sql);
+			// // System.out.println("build time: "+(System.currentTimeMillis()
+			// // - startTime) + "ms");
+			// // startTime = System.currentTimeMillis(); //获取开始时间
+			// state.executeUpdate(sql);
+			// }
+
+			String tableName = "gps_location_tokudb";
+			if (id % 2 == 0) {
+				// tableName = "gps_location_myisam_mutldisk2";
+			}
+			// 拼成一条sql语句发送 tokudb innodb myisam
+			String sql = String
+					.format("insert into "
+							+ tableName
+							+ "(`DeviceId`,`DeviceTime`,"
+							+ "`Longitude`,`Latitude`,`Speed`,`Direction`,`Status`,`SatelliteCount`,`LBS`)values");
+			int times = execTimesPerThread;
+			for (int j = 0; j < times; j++) {
+
+				StringBuffer sb = new StringBuffer();
+				sb.append(sql);
+
+				int cout = oneSqlInsertValuesLen;
+				for (int i = 0; i < cout; i++) {
+					sb.append(String.format(
+							"('%s',%d,%f,%f,%d,%d,%d,%d,'%s'),", getDeviceId(),
+							System.currentTimeMillis() / 1000, getLong(),
+							getLatit(), getSpeed(), getDirection(),
+							getStatus(), getSatelliteCount(), getLBS()));
+
+					// System.out.println("build time: "+(System.currentTimeMillis()
+					// - startTime) + "ms");
+					// startTime = System.currentTimeMillis(); //获取开始时间
+
+					// sb.append("('00000000000222050184',1552226307,87.622294,36.484341,5122,12215,26,32,'e5m2LI0Y'),");
+				}
+				// System.out.println(sb.toString());
+
+				long startTime = System.currentTimeMillis();
+				state.execute(sb.toString().substring(0, sb.length() - 1));
+				System.out.println(cout + " insert OK "
+						+ (System.currentTimeMillis() - startTime) + "ms");
+			}
+
+			// System.out.println("exec time: "+(System.currentTimeMillis() -
+			// startTime) + "ms");
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	public static void execQueryTest0(Connection conn) {
+		try {
+			String did = getDeviceId();
+			// String sql = "select * from gps_location_tokudb where deviceid='"
+			// + did + "' limit 4000";
+			String sql = "select DeviceTime,Longitude,Latitude from gps_location_tokudb where deviceid='"
+					+ did + "' limit " + queryLimit;
+			// System.out.println(sql);
+			PreparedStatement pst = null;
+			long startTime = System.currentTimeMillis();
+			pst = (PreparedStatement) conn.prepareStatement(sql);
+
+			ResultSet rs = pst.executeQuery();
+			int count = 0;
+			while (rs.next()) {
+				// 将查询出的内容添加到list中,其中userName为数据库中的字段名称
+				count++;
+			}
+
+			System.out.println("query " + did + " count " + count + " "
+					+ (System.currentTimeMillis() - startTime) + "ms");
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	public static void execQueryTest() {
+		try {
+			Class.forName("com.mysql.jdbc.Driver");
+			Connection conn = (Connection) DriverManager
+					.getConnection(
+							"jdbc:mysql://192.168.1.187:3306/gps?characterEncoding=UTF-8",
+							"root", "jrtk.net");
+
+			for (int i = 0; i < execTimesPerThread; i++) {
+				execQueryTest0(conn);
+			}
+
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+
+	}
+
+	static String flag = "query";
+	
+	static int threadNumber = 50;
+	static int execTimesPerThread = 10;
+
+	static int queryLimit = 4000;
+	static int oneSqlInsertValuesLen = 2000;
+	public static void main(String[] args) {
+		try {
+			if (args.length > 0) {
+				try {
+					flag = args[0];// insert query
+					threadNumber = Integer.parseInt(args[1]);
+					execTimesPerThread = Integer.parseInt(args[2]);
+					oneSqlInsertValuesLen = Integer.parseInt(args[3]);
+					if (flag.equals("query")) {
+						queryLimit = Integer.parseInt(args[3]);
+					} else {
+						oneSqlInsertValuesLen = Integer.parseInt(args[3]);
+					}
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+			long startTime = System.currentTimeMillis(); // 获取开始时间
+
+			System.out.println("start threadNumber " + threadNumber + " "
+					+ flag + " thread");
+			final CountDownLatch countDownLatch = new CountDownLatch(
+					threadNumber);
+			for (int i = 0; i < threadNumber; i++) {
+				final int threadID = i;
+				new Thread() {
+					public void run() {
+						if (flag.equals("insert")) {
+							execSql(threadID);
+						} else if (flag.equals("query")) {
+							execQueryTest();
+						} else {
+							System.out
+									.println("args error;eg: insert|query threadNumber execTimesPerThread oneSqlInsertValuesLen|queryLimit");
+							System.exit(0);
+						}
+
+						// execTransSql();
+						System.out.println(String.format(
+								"threadID:[%s] finished!!", threadID));
+						countDownLatch.countDown();
+					}
+				}.start();
+			}
+			countDownLatch.await();
+			oneSqlInsertValuesLen = flag.equals("query") ? 1
+					: oneSqlInsertValuesLen;
+			System.out
+					.println("time: "
+							+ (System.currentTimeMillis() - startTime)
+							+ "ms threadNumber:"
+							+ threadNumber
+							+ " total:"
+							+ (threadNumber * execTimesPerThread * oneSqlInsertValuesLen) + " " 
+							+ (flag.equals("query") ? "queryLimit:" + queryLimit : " oneSqlInsertValuesLen:" + oneSqlInsertValuesLen));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+
+	}
+}

+ 82 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsData.java

@@ -0,0 +1,82 @@
+package com.renlianiot.demo.gps;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
+import java.util.Random;
+
+public class GpsData extends GpsRequestAbstruct {
+	int time;
+	int longitude;
+	int latitude;
+	byte speed;
+	short direction;
+	byte[] LBS = new byte[9];
+	byte status;
+
+	public GpsData(short serialNumber) {
+		this.gpsHeader = new GpsHeader((byte) 0x02, (short) 25, serialNumber);
+		this.time = (int) (System.currentTimeMillis() / 1000);
+		this.longitude = getLong();
+		
+		this.latitude = getLatit();
+//		System.out.println("γ¶È:" + this.latitude);
+//		System.out.println("¾­¶È:" + this.longitude);
+		this.direction = getDirection();
+		this.speed = (byte) getSpeed();
+		this.LBS = Utils.hexStringToBytes(Utils.randomHexString(18));
+		this.status = (byte) getStatus();
+	}
+	public GpsData(short serialNumber, int longitude, int latitude) {
+		this.gpsHeader = new GpsHeader((byte) 0x02, (short) 25, serialNumber);
+		this.time = (int) (System.currentTimeMillis() / 1000);
+		this.longitude = longitude;
+		this.latitude = latitude;
+//		System.out.println("γ¶È:" + this.latitude);
+//		System.out.println("¾­¶È:" + this.longitude);
+		this.direction = getDirection();
+		this.speed = (byte) getSpeed();
+		this.LBS = Utils.hexStringToBytes(Utils.randomHexString(18));
+		this.status = (byte) getStatus();
+	}
+	static int getLong() {
+		int max = 324000000;
+		int min = 0;
+		int s = new Random().nextInt(max) % (max - min + 1) + min;
+		return new Random().nextInt(2) == 0 ? -s : s;
+	}
+
+	static int getLatit() {
+		int max = 162000000;
+		int min = 0;
+		int s = new Random().nextInt(max) % (max - min + 1) + min;
+		return new Random().nextInt(2) == 0 ? -s : s;
+	}
+
+	public static short getStatus() {
+		return (short) (0 + Math.random() * (3 - 0 + 1));
+	}
+
+	public static short getDirection() {
+		return (short) (1 + Math.random() * (65535 - 1 + 1));
+	}
+
+	public static int getSpeed() {
+		return (int) (1 + Math.random() * (255 - 1 + 1));
+	}
+
+
+
+	@Override
+	public byte[] toByteArray() {
+		ByteBuf buf = Unpooled.buffer(25);
+		buf.writeInt(this.time);
+		buf.writeInt(this.latitude);
+		buf.writeInt(this.longitude);
+		buf.writeByte(this.speed);
+		buf.writeShort(this.direction);
+		buf.writeBytes(this.LBS);
+		buf.writeByte(this.status);
+		return buf.array();
+	}
+}

+ 71 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsDecoder.java

@@ -0,0 +1,71 @@
+package com.renlianiot.demo.gps;
+
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import com.mysql.jdbc.Util;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.util.ReferenceCountUtil;
+
+public class GpsDecoder extends ByteToMessageDecoder {
+
+	private enum State {
+		Header, Body
+	}
+
+	private State state = State.Header;
+	GpsHeader gpsHeader;
+
+	@Override
+	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
+			List<Object> out) throws Exception {
+		switch (state) {
+		case Header:
+			if (in.readableBytes() < 7) {
+				return;
+			}
+			gpsHeader = new GpsHeader();
+			gpsHeader.magic = Utils.shortToByte(in.readShort());
+			gpsHeader.protocolNum = in.readByte();
+			gpsHeader.len = in.readShort();
+			gpsHeader.serialNumber = in.readShort();
+			state = State.Body;
+		case Body:
+			if (in.readableBytes() < gpsHeader.len - 2) {
+				return;
+			}
+			ByteBuf buf = in.readBytes(gpsHeader.len - 2);
+			
+			byte[] body = ByteBufUtil.getBytes(buf);
+			 ReferenceCountUtil.release(buf);
+
+			if (ctx.channel().hasAttr(TimeClientHandler.attrKey2)) {
+				StringBuffer sBuffer = new StringBuffer();
+				sBuffer.append(ctx.channel().hashCode());
+				sBuffer.append("[");
+				sBuffer.append(new Timestamp(System.currentTimeMillis()).toString()/*new SimpleDateFormat("HH:mm:ss").format(new Date())*/);
+				sBuffer.append("]");
+				sBuffer.append("recv magic:");
+				sBuffer.append(Utils.bytesToHex(gpsHeader.magic));
+				sBuffer.append(", protocolNum:");
+				sBuffer.append(gpsHeader.protocolNum);
+				sBuffer.append(", len:");
+				sBuffer.append(gpsHeader.len);
+				sBuffer.append(", serialNumber:");
+				sBuffer.append(gpsHeader.serialNumber);
+				sBuffer.append(", body:");
+				sBuffer.append(Utils.bytesToHex(body));
+				System.out.println(sBuffer.toString());
+			}
+			state = State.Header;
+
+		}
+	}
+
+}

+ 55 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsEncoder.java

@@ -0,0 +1,55 @@
+package com.renlianiot.demo.gps;
+
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+public class GpsEncoder extends MessageToByteEncoder<GpsRequest> { 
+	
+	@Override
+	protected void encode(ChannelHandlerContext ctx, GpsRequest gpsRequest, ByteBuf out)
+			throws Exception {
+		out.writeBytes(gpsRequest.data.gpsHeader.toByteArray());
+		out.writeBytes(gpsRequest.data.toByteArray());
+		
+		if (ctx.channel().hasAttr(TimeClientHandler.attrKey2)) 
+		{
+			StringBuffer sBuffer = new StringBuffer();
+			sBuffer.append(ctx.channel().hashCode());
+			sBuffer.append("[");
+			sBuffer.append(new Timestamp(System.currentTimeMillis()).toString());
+			sBuffer.append("]");
+			sBuffer.append("send magic:");
+			sBuffer.append(Utils.bytesToHex(gpsRequest.data.gpsHeader.magic));
+			sBuffer.append(", protocolNum:");
+			sBuffer.append(gpsRequest.data.gpsHeader.protocolNum);
+			sBuffer.append(", len:");
+			sBuffer.append(gpsRequest.data.gpsHeader.len);	
+			sBuffer.append(", serialNumber:");
+			sBuffer.append(gpsRequest.data.gpsHeader.serialNumber);
+			sBuffer.append(", body:");
+			sBuffer.append(Utils.bytesToHex(gpsRequest.data.toByteArray()));
+			
+			
+			System.out.println(sBuffer.toString());
+		}
+	}
+	
+
+}
+
+
+
+
+
+
+
+
+
+
+

+ 32 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsHeader.java

@@ -0,0 +1,32 @@
+package com.renlianiot.demo.gps;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+
+
+public class GpsHeader {
+	public byte[] magic = {0x67, 0x67};
+	public byte protocolNum;
+	public short len;
+	public short serialNumber = 0;
+	public GpsHeader() {
+		
+	}
+	public GpsHeader(byte protocolNum, short bodyLen, short serialNumber) {
+		this.protocolNum = protocolNum;
+		this.len = (short) (bodyLen + 2);
+		this.serialNumber = serialNumber;
+		this.serialNumber++;
+	}
+	public byte[] toByteArray() {
+		 ByteBuf buf = Unpooled.buffer(7);
+		 buf.writeBytes(magic);
+		 buf.writeByte(protocolNum);
+		 buf.writeShort(len);
+		 buf.writeShort(serialNumber);
+		 return buf.array();
+	}
+}

+ 24 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsHeartBeat.java

@@ -0,0 +1,24 @@
+package com.renlianiot.demo.gps;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
+public class GpsHeartBeat extends GpsRequestAbstruct {
+
+	short status;
+	public GpsHeartBeat(short serialNumber) {
+		this.gpsHeader = new GpsHeader((byte)0x03, (short)2, serialNumber);
+		this.status = getStatus();
+//		this.time = (int)(System.currentTimeMillis() / 1000);
+	}
+	public static short getStatus() {
+		return (short) (0 + Math.random() * (2047 - 0 + 1));
+	}
+	@Override
+	public byte[] toByteArray() {
+		ByteBuf buf = Unpooled.buffer(2);
+		buf.writeShort(status);
+		return buf.array();
+	}
+
+}

+ 28 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsLogin.java

@@ -0,0 +1,28 @@
+package com.renlianiot.demo.gps;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+
+
+public class GpsLogin extends GpsRequestAbstruct {
+	byte[] imei = new byte[8];
+	byte language = 0x00;
+	
+	
+	public GpsLogin(String imei, short serialNumber) {
+		this.gpsHeader = new GpsHeader((byte) 0x01, (short)9, serialNumber);
+		this.imei = Utils.hexStringToBytes(imei);
+	}
+	@Override
+	public byte[] toByteArray() {
+		ByteBuf buf = Unpooled.buffer(9);
+		buf.writeBytes(imei);
+		buf.writeByte(language);
+		return buf.array();
+	}
+}

+ 16 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsRequest.java

@@ -0,0 +1,16 @@
+package com.renlianiot.demo.gps;
+
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+
+
+public class GpsRequest {
+	public GpsRequest(GpsRequestAbstruct gps) {
+		this.data = gps;
+	}
+	public GpsRequestAbstruct data;
+}

+ 0 - 0
SchoolRFIDTcp/src/com/renlianiot/demo/gps/GpsRequestAbstruct.java


Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov