【发布时间】:2018-02-20 05:17:52
【问题描述】:
我是套接字编程的新手,对 I/O 类不是很熟悉。
在下面的代码中,我正在制作一个简单的套接字程序,并使用while循环使其能够接受clientSocket不止一次。代码在第一次迭代中执行得很好,而当它到达 header = in.nextLine() 时抛出 NoSuchElementException (在线程的 run 方法中)。我认为该方法是阻塞的,应该等待输入?当我调用 next() 时会发生类似的事情。
谁能帮我理解这个?我将不胜感激!
public static void main(String args[]) throws IOException {
Socket clientSocket = null;
ServerSocket listenSocket = new ServerSocket(8888);
int num = 0;
try {
while (true) {
clientSocket = listenSocket.accept();
new ClientSocket(clientSocket, num++).start();
}
} finally {
listenSocket.close();
}
}
private static class ClientSocket extends Thread {
private Socket socket;
private int numOfSocket;
public ClientSocket(Socket s, int num) {
socket = s;
numOfSocket = num;
}
public void run() {
//get file location
String header;
String fileLocation = null;
Scanner in = null;
Scanner scanner = null;
PrintWriter out = null;
try {
// Get header && extract file location
in = new Scanner(socket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
header = in.nextLine();
System.out.println(header);
String[] headerArr = header.split(" ");
String url = headerArr[1];
fileLocation = url.substring(1);
System.out.println(fileLocation);
// Try to get the file
FileInputStream file = new FileInputStream(fileLocation);
System.out.println("file found");
out.println("HTTP/1.1 200 OK\n");
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException e) {
System.out.print("file not found");
out.println("HTTP/1.1 404 File not found\n");
try {
scanner = new Scanner(new File("fileNotFound.html"));
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException a) {
System.out.println(a.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
in.close();
out.close();
if (scanner != null) {
scanner.close();
}
try {
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
更多说明: 所以我在 Netbeans IDE 中运行它,并使用 Chrome 浏览器作为客户端对其进行测试。它在最初的几次尝试中运行良好,然后开始抛出异常。客户端不受影响,仍然可以得到正确的响应。只是服务器端受到影响。这是来自控制台的消息。
块引用
GET /hah HTTP/1.1
hah
file not foundGET /favicon.ico HTTP/1.1
favicon.ico
file not foundGET /test.html HTTP/1.1
test.html
file found
Exception in thread "Thread-3" Exception in thread "Thread-5" Exception
in thread "Thread-4" java.util.NoSuchElementException: No line found
块引用
【问题讨论】:
-
当我尝试执行你的代码时,我没有得到这样的异常。我所做的:将您的代码复制到类中,运行,telnet 到端口 8888 上的 localhost 并写入字符串
<some text><space><some text>。只要我没有您的代码要查找的任何文件,我就会遇到异常,但正确的FileNotFoundException。那么您能否添加一些有关如何运行/测试的信息? -
HTML 中的行终止符是
\r\n,而不是\n。您不需要整个Scanner来复制文件。 -
感谢您的评论! @Evgeny 我已经发布了我的控制台日志。看看你有没有同样的问题?
-
@EJP 你能再解释一下吗?谢谢!
-
如果我经常在 Chrome 中推送重新加载,我可以重现这种异常。因此,假设问题是 chrome 在发送行尾之前关闭了连接,结果扫描仪会在流中没有更多可用行时抛出异常(因为它已关闭)。