我有一个任务,首先编写一个多线程客户端服务器应用程序,然后用很多客户端测试它(100个客户端每个发送1000条消息)。所以我已经正常工作了控制台客户端服务器。客户端有两个线程,一个用于输入,另一个用于输出。现在我开始写测试了。在我看来,它的工作模式应该是:执行应该等待接受新客户端的服务器线程,然后执行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.服务器是多线程的,支持许多客户端。现在我只想从源代码中测试它。
发布于 2012-06-14 17:53:47
您的防火墙是否打开,允许该端口上的传入连接?
另外,您并不是真正地复制客户机-服务器架构,因为只有一个套接字被所有“客户端”线程共享。这可能是错误的来源(访问同一个对象的多个线程--在本例中是流)。
请参阅Oracle提供的有关如何使用单独的进程和套接字正确设置客户机/服务器演示的文档:http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html --这将允许您模拟实际发生的情况,并附带对代码的出色解释。
https://stackoverflow.com/questions/11037761
复制相似问题