gpt4 book ai didi

java - 通过 JUnit 的 Socket 进行服务器-客户端数据交换测试

转载 作者:行者123 更新时间:2023-11-30 06:30:32 25 4
gpt4 key购买 nike

我正在尝试在 JUnit 类中通过套接字测试服务器-客户端数据交换。我遵循的是:

private static Socket clientSocket;
private static InputStream is;
private static PrintWriter pw;
private static Socket serverSocket;
private static final int PORT_NUMBER = 1154;

@BeforeClass
public static void init() throws IOException {
ServerSocket sSocket = new ServerSocket(PORT_NUMBER);
clientSocket = new Socket("localhost", PORT_NUMBER);
is = clientSocket.getInputStream();

serverSocket = sSocket.accept();
OutputStream os = serverSocket.getOutputStream();
pw = new PrintWriter(os, true);
}

@Test
public void testXPackage() throws IOException {
for (int packageByte : X_PACKAGE) {
pw.write(packageByte);
}

while (is.available() > 0) {
System.out.println(is.read());
}
}

但是is.available()始终为0。我缺少什么?

最佳答案

PrintWriter pm 正在缓冲输出。完成写入后必须调用 pm.flush()。例如:

@Test
public void testXPackage() throws IOException {
for (int packageByte : X_PACKAGE) {
pw.write(packageByte);
}
pm.flush(); // <<--- added this line.

while (is.available() > 0) {
System.out.println(is.read());
}
}

关于java - 通过 JUnit 的 Socket 进行服务器-客户端数据交换测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46246695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com