服务器监听端口代码:
while (true) {
try {
Socket connection = server.accept();
FileUtils.writeLocal(TimeUtils.getCurrentTime());
FileOutputStream fos = new FileOutputStream("serverlog.txt", true);
threadcount++;
fos.write((connection.getInetAddress() + ":" + connection.getPort() + " threadcount: " + threadcount)
.getBytes());
fos.write("\r\n".getBytes());
fos.flush();
fos.close();
pool.submit(new HTTPHandler(connection, header));
} catch (IOException e) {
logger.log(Level.WARNING, "Exception accepting connection", e);
} catch (RuntimeException e) {
logger.log(Level.SEVERE, "Unexpected error", e);
}
}
客户端链接服务器代码:
for (; j < 105000; j++) {
new Thread() {
public void run() {
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
startSocket(j);
};
}.start();
}
发现启动服务器后,再启动客户端,总会出现connetion refused:connect的异常。服务器 fos.write((connection.getInetAddress() + ":" + connection.getPort() + " threadcount: " + threadcount)将连接数写入文件,但是这个连接的数量不稳定,怎么办?