我是socket编程的新手,对I / O类不是很熟悉。
在下面的代码中,我正在创建一个简单的套接字程序并使用while循环使其能够接受clientSocket多次。代码在第一次迭代中执行得很好,当它到达header = in.nextLine()时(在线程的run方法中)抛出NoSuchElementException。我认为该方法是阻塞的,应该等待输入?当我调用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
块引用
答案 0 :(得分:0)
所以最终我发现了。这是客户端的问题(这是Chrome浏览器)
当Chrome访问我的服务器时,实际上是发送了2个请求。使用我的原始请求之一,另一个是自动生成以获取元数据。由于我的服务器简单且用于教育目的,因此它不是为处理不期望的错误而设计的。
所以结论是这些代码在其原始目的下工作正常,但在实际情况下需要更加强大。