Netty-TCP 04.发消息

发布时间 2023-06-30 20:01:21作者: 米虫2022

本文是使用Netty开发一个简单的TCP通讯(聊天)应用程序的第【4】部分,主要测试客户端和服务端的通讯。

服务端

下面是服务端测试代码:

/**
 * @author michong
 */
public class TCPServer {

    public static void main(String[] args) {
        TCPServerBootstrap bootstrap = new TCPServerBootstrap("localhost", 8081);
        bootstrap.start();
    }
}

客户端

下面是客户端测试代码:

/**
 * @author michong
 */
public class TCPClient {

    public static void main(String[] args) throws InterruptedException {
        TCPClientBootstrap bootstrap = new TCPClientBootstrap("localhost", 8081);
        Channel channel = bootstrap.start();

        System.out.println("请在控制台中输入需要发送的内容(输入exit退出程序)");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String text = scanner.nextLine();
            if ("exit".equalsIgnoreCase(text)) {
                break;
            }
            channel.writeAndFlush(new Packet(Pkt.TEXT, text.getBytes()));
        }
        scanner.close();
        bootstrap.stop();
    }
}

发消息

  1. 先启动服务端
  2. 在启动客户端
  3. 在客户端的控制台输入需要发送的内容,输入exit则退出客户端

收发日志:

  • 服务端:
服务端启动成功 => host=localhost, port=8081
收到消息:类型=1,内容=hello world
收到消息:类型=1,内容=收到
  • 客户端:
客户端启动成功 => host=localhost, port=8081
请在控制台中输入需要发送的内容(输入exit退出程序)
hello world
收到消息:类型=1,内容=OK.
收到
收到消息:类型=1,内容=OK.
exit