gpt4 book ai didi

java - 多线程测试

转载 作者:行者123 更新时间:2023-11-28 20:57:15 25 4
gpt4 key购买 nike

我的任务是首先编写一个多线程客户端服务器应用程序,然后用大量客户端(100 个客户端,每个客户端发送 1000 条消息)对其进行测试。所以我已经正常工作控制台客户端服务器。客户端有两个线程,一个用于输入,另一个用于输出。现在我开始写测试。在我看来,它的工作模式应该是这样的:执行应该等待接受新客户端的服务器线程,之后我将执行 InputThreads(将其连接到服务器)并在循环中写入测试协议(protocol)。我说得对吗?

所以我写了这样的东西:

public class ServerLoadTest {
private static final Logger LOG = Logger.getLogger(ServerLoadTest.class);
private ExecutorService clientExec = Executors.newFixedThreadPool(100);
private ExecutorService serverExec = Executors.newFixedThreadPool(100);

@Test
public void test() throws IOException, JAXBException, XMLStreamException, ParserConfigurationException, SAXException, InterruptedException {
LOG.trace("Start testing");
serverExec.execute(new TestServerThread());

for (int i = 0; i < 100; i++) {
clientExec.execute(new TestClientThread());
}

Assert.assertTrue(true);
LOG.trace("All working fine");
clientExec.shutdown();
}

}


class TestClientThread implements Runnable {
private static final Logger LOG = Logger.getLogger(TestClientThread.class);
private ExecutorService outputExec = Executors.newFixedThreadPool(2);

public TestClientThread() {
new Thread(this);
}

@Override
public void run() {

try {
LOG.trace("Starting Socket");
Socket s = new Socket("localhost", 4444);
OutputThread spamming = new OutputThread(s, new PrintWriter(s.getOutputStream(), true), new BufferedReader(
new InputStreamReader(s.getInputStream())));
exec.execute(spamming);

spamming.getOut().println("HO HO Ho HO HO");

InputThread getSpamAnswer = new InputThread(s, new BufferedReader(new InputStreamReader(s.getInputStream())));
outputExec.execute(getSpamAnswer);

} catch (IOException | JAXBException | XMLStreamException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
}
}

class TestServerThread implements Runnable {
private Server king = mock(Server.class);

public TestServerThread() {
new Thread(this);
}

@SuppressWarnings("static-access")
@Override
public void run() {
try {
king.main(null);
} catch (IOException | JAXBException | ParserConfigurationException | SAXException e) {
Assert.assertFalse(false);
}
}
}

首先,服务器上有很多 LOG.trace,但我在控制台中没有,当我调试时,我收到一个异常,我的客户端无法连接(我认为它没有时间为了这)。我应该如何同步它?

附言服务器是多线程的,支持很多客户端。现在我只想从源头上测试它。

最佳答案

您的防火墙是否打开允许该端口上的传入连接?

此外,您并没有真正复制客户端-服务器架构,因为只有一个套接字被所有“客户端”线程共享。这可能是错误的来源(多个线程访问同一个对象 - 在本例中是一个流)。

请参阅来自 Oracle 的文档,了解如何使用单独的进程和套接字正确设置客户端/服务器演示:http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html这将使您能够模拟实际发生的情况,并附带对代码的很好解释。

关于java - 多线程测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037761/

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