You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java@Test单元测试中Socket服务端与客户端无法同时启动问题

问题根因

核心问题是GameServer的start方法直接在测试主线程中同步执行,导致后续客户端创建、连接的代码完全没有运行机会:

  • server.start(9000) 方法内部的while(true)死循环 + serverSocket.accept()是阻塞方法,这行代码调用后会直接卡住测试主线程,永远走不到后面创建GameClient、发起连接的代码,自然不会有客户端连接上来,也不会打印子线程名称。

修复方案

  1. 把GameServer的启动逻辑放到独立子线程中执行,不要占用测试主线程,这样后续的客户端代码才能正常运行:
@Test
public void serverTest() throws IOException, InterruptedException {
    GameServer server = new GameServer();
    // 单独开线程启动服务端,不阻塞主线程
    new Thread(() -> {
        try {
            server.start(9000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }).start();
    // 加短暂等待,确保服务端启动完成再连客户端,避免连接失败
    Thread.sleep(1000);
    
    GameClient client1 = new GameClient();
    GameClient client2 = new GameClient();
    client1.startConnection("localhost", 9000);
    client2.startConnection("localhost", 9000);
    client1.sendMessage("Hey I am client 1");
    client2.sendMessage("Hey I am client 2");
    // 加等待,给服务端子线程足够时间处理消息打印,避免测试提前结束进程被销毁
    Thread.sleep(1000);
}
  1. 修复GameClientHandler内部的多余readLine调用问题,你当前的代码会漏掉第一条客户端消息:
// 原错误代码:第一行readLine读完直接丢弃,进入循环后又读下一行
// String inputLine = in.readLine();
// while ((inputLine = in.readLine()) != null){
// 修改后:
String inputLine;
while ((inputLine = in.readLine()) != null){
    System.out.println(inputLine);
}

内容的提问来源于stack exchange,提问作者user16037629

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:54:00