shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.walker.tcp;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
 
public class HelloClient {
 
       public static String host = "127.0.0.1";
       public static int port = 7878;
 
         /**
          * @param args
          * @throws InterruptedException
          * @throws IOException
          */
         public static void main(String[] args) throws InterruptedException, IOException {
             EventLoopGroup group = new NioEventLoopGroup();
             try {
                 Bootstrap b = new Bootstrap();
                 b.group(group).channel(NioSocketChannel.class).handler(new HelloClientInitializer());
 
                 // 连接服务端
//                 Channel ch = b.connect(host, port).sync().channel();
                 Channel ch = b.connect(host, port).sync().channel();
 
                 // 发起模拟登陆
                 StringBuilder sb = new StringBuilder();
                 sb.append("IWAP00");
//            sb.append("helloClient");
//            sb.append("d1234567");
                 sb.append("000001");
                 sb.append("#");
                 ch.writeAndFlush(sb.toString());
 
                 // 控制台输入
                 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                 for (;;) {
                     String line = in.readLine();
                     if (line == null) {
                         continue;
                     }
                     /*
                      * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
                      * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
                      * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
                      * */
//                     ch.writeAndFlush(line + "\r\n");
                     ch.writeAndFlush(line + "#");
                 }
             } finally {
                 // The connection is closed automatically on shutdown.
                 group.shutdownGracefully();
             }
         }
}