|
@@ -0,0 +1,42 @@
|
|
|
|
|
+package com.xiaobao.gateway.protocol.udp;
|
|
|
|
|
+
|
|
|
|
|
+import io.netty.buffer.Unpooled;
|
|
|
|
|
+import io.netty.channel.ChannelHandlerContext;
|
|
|
|
|
+import io.netty.channel.SimpleChannelInboundHandler;
|
|
|
|
|
+import io.netty.channel.socket.DatagramPacket;
|
|
|
|
|
+import io.netty.util.CharsetUtil;
|
|
|
|
|
+
|
|
|
|
|
+import java.net.InetSocketAddress;
|
|
|
|
|
+
|
|
|
|
|
+public class ClientProxyHandler extends SimpleChannelInboundHandler<DatagramPacket> {
|
|
|
|
|
+ @Override
|
|
|
|
|
+ protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
|
|
|
|
|
+ String msg = packet.content().toString(CharsetUtil.UTF_8);
|
|
|
|
|
+ System.out.println("Received data from client: " + msg);
|
|
|
|
|
+ InetSocketAddress client = packet.sender();
|
|
|
|
|
+ String newMsg = System.currentTimeMillis() + "\n";
|
|
|
|
|
+ DatagramPacket responsePacket = new DatagramPacket(Unpooled.copiedBuffer(newMsg.getBytes(CharsetUtil.UTF_8)), client);
|
|
|
|
|
+ ctx.writeAndFlush(responsePacket).addListener((future) -> {
|
|
|
|
|
+ if (future.isSuccess()) {
|
|
|
|
|
+ System.out.println("回写客户端成功");
|
|
|
|
|
+ } else {
|
|
|
|
|
+ System.out.println("回写客户端失败");
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+ if (msg.startsWith("close")) {
|
|
|
|
|
+ ctx.channel().close();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Override
|
|
|
|
|
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
|
|
|
|
+ System.out.println("Client connected");
|
|
|
|
|
+ super.channelActive(ctx);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Override
|
|
|
|
|
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
|
|
|
|
+ System.out.println("Client disconnected");
|
|
|
|
|
+ super.channelInactive(ctx);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|