我有一个任务,首先编写一个多线程客户端服务器应用程序,然后用很多客户端(每个发送1000条消息的100个客户端)测试它。所以我有正确的控制台客户端服务器。客户端有两个线程用于输入其他输出。现在我开始写测试。在我看来,它的工作模式应该是这样的:执行服务器线程,应该等待接受新客户端,之后,我会执行InputThreads(连接到服务器)并在循环中写入测试协议。我对吗?多线程测试
所以,我写的是这样的:
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的,但是我没有任何的它的控制台,当我调试我收到一个异常我的客户无法连接(我认为它没有时间)。我应该如何同步这个?
P.S.服务器是多线程的,并支持许多客户端。现在我只想从源头测试它。
是的,我已经看到了。我的服务器不仅支持一个客户端。我认为问题在测试中。服务器不能及时启动。在Java单元测试中是否有任何工具来测试多线程。 –
在代码的开始处,您启动一个服务器线程,然后在同一进程中启动多个客户端线程*。这并不反映客户机/服务器体系结构的正常工作方式,也不是测试的良好基础。他们应该是单独的程序。另外,如果你担心ServerSocket没有及时准备好,那么我建议你在'run()'或'main()'的最开始处创建套接字,以便它立即侦听。如果这还不够快,您可以在创建客户端之前调用'sleep()'一秒钟。 – kaz
和我提供的文档的底部演示了如何让服务器一次接受多个客户端连接 - 它具有您需要的信息。 – kaz