本文是使用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(); } }
发消息
- 先启动服务端
- 在启动客户端
- 在客户端的控制台输入需要发送的内容,输入exit则退出客户端
收发日志:
- 服务端:
服务端启动成功 => host=localhost, port=8081 收到消息:类型=1,内容=hello world 收到消息:类型=1,内容=收到
- 客户端:
客户端启动成功 => host=localhost, port=8081 请在控制台中输入需要发送的内容(输入exit退出程序) hello world 收到消息:类型=1,内容=OK. 收到 收到消息:类型=1,内容=OK. exit
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)