随笔 - 59,  文章 - 1,  评论 - 0,  阅读 - 24152

本文是使用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
posted on   $$X$$  阅读(46)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

点击右上角即可分享
微信分享提示