ошибка в моем Java-коде для веб-сервера

#java

#java

Вопрос:

Я продолжаю получать эти ошибки, и я понятия не имею, почему. Я работал над этим более 4 часов, и я все еще не могу исправить эту ошибку. я, честно говоря, не знаю, что я здесь делаю не так.

 WebServer.java:84: error: class, interface, or enum expected
StringTokenizer tokens = new StringTokenizer(requestLine);
^
WebServer.java:85: error: class, interface, or enum expected
tokens.nextToken(); // skip over the method, which should be "GET"
^
WebServer.java:86: error: class, interface, or enum expected
String fileName = tokens.nextToken();
^
WebServer.java:89: error: class, interface, or enum expected
fileName = "."   fileName;
^
WebServer.java:92: error: class, interface, or enum expected
FileInputStream fis = null;
^
WebServer.java:93: error: class, interface, or enum expected
boolean fileExists = true;
^
WebServer.java:94: error: class, interface, or enum expected
        try {
        ^
WebServer.java:96: error: class, interface, or enum expected
} catch (FileNotFoundException e) {
^
WebServer.java:98: error: class, interface, or enum expected
}
^
WebServer.java:102: error: class, interface, or enum expected
String contentTypeLine = null;
^
WebServer.java:103: error: class, interface, or enum expected
String entityBody = null;
^
WebServer.java:104: error: class, interface, or enum expected
if (fileExists) {
^
WebServer.java:106: error: class, interface, or enum expected
contentTypeLine = "Content-type: "   contentType( fileName )   CRL
^
WebServer.java:107: error: class, interface, or enum expected
}
^
WebServer.java:110: error: class, interface, or enum expected
contentTypeLine = "Content-type: "   "text/html"   CRLF;
^
WebServer.java:111: error: class, interface, or enum expected
entityBody = "<HTML>"  
^
WebServer.java:114: error: class, interface, or enum expected
}
^
WebServer.java:119: error: class, interface, or enum expected
os.writeBytes(contentTypeLine);
^
WebServer.java:121: error: class, interface, or enum expected
os.writeBytes(CRLF);
^
WebServer.java:123: error: class, interface, or enum expected
if (fileExists) {
^
WebServer.java:125: error: class, interface, or enum expected
fis.close();
^
WebServer.java:126: error: class, interface, or enum expected
}
^
WebServer.java:129: error: class, interface, or enum expected
}
^
WebServer.java:136: error: class, interface, or enum expected
 int bytes = 0;
 ^
WebServer.java:138: error: class, interface, or enum expected
 while((bytes = fis.read(buffer)) != -1 ) {
 ^
WebServer.java:140: error: class, interface, or enum expected
 }
 ^
WebServer.java:147: error: class, interface, or enum expected
    }
    ^
WebServer.java:150: error: class, interface, or enum expected
    }
    ^
WebServer.java:153: error: class, interface, or enum expected
    }
    ^
WebServer.java:156: error: class, interface, or enum expected
    }
    ^
WebServer.java:159: error: class, interface, or enum expected
    }
    ^
WebServer.java:161: error: class, interface, or enum expected
  }
  ^
32 errors
  

вот исходный код

 import java.io.* ;
import java.net.* ;
import java.util.* ;

public final class WebServer{
  public static void main(String argv[]) throws Exception
  {
    // Set the port number.
    int port = 6789;

    // Establish the listen socket.
    ServerSocket listenSocket = new ServerSocket(port);

    //Process HTTP service requests in an infinite loop
    while (true) {
      // Listen for a TCP connection request
      Socket connectionSocket = listenSocket.accept();

      // Construct an object to process the HTTP request message
      HttpRequest request = new HttpRequest(connectionSocket);

      // Create a new thread to process the request.
      Thread thread = new Thread(request);

      // Start the thread.
      thread.start();
    }

  }
}

final class HttpRequest implements Runnable
{
  final static String CRLF = "rn";
  Socket socket;

  // Constructor
  public HttpRequest(Socket socket) throws Exception
  {
    this.socket = socket;
  }

  // Implement the run() method of the Runnable interface.
  public void run()
  {
    try 
      {
    processRequest();
      }
    catch (Exception e) 
      {
    System.out.println(e);
      }
  }
   private void processRequest() throws Exception
  {
    // Get a reference to the socket's input and output streams.
    InputStream is = socket.getInputStream();
    DataOutputStream os = new DataOutputStream(socket.getOutputStream());

    // Set up input stream filters.
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    //Get the request line of the HTTP request message.
    String requestLine = br.readLine();

    // Display the request line.
    System.out.println();
    System.out.println(requestLine);

    // Get and display the header lines.
    String headerLine = null;
    while ((headerLine = br.readLine()).length() != 0) {
            System.out.println(headerLine);
}
    // Close streams and socket.
    os.close();
    br.close();
    socket.close();
}
}

// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();

// Prepend a "." so that file request is within the current directory.
fileName = "."   fileName;

// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
    try {
        fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
        fileExists = false;
}

// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK"   CRLF;
contentTypeLine = "Content-type: "   contentType( fileName )   CRLF;
} 
else {
statusLine = "HTTP/1.0 404 Not Found"   CRLF;
contentTypeLine = "Content-type: "   "text/html"   CRLF;
entityBody = "<HTML>"  
"<HEAD><TITLE>Not Found</TITLE></HEAD>"  
"<BODY>Not Found</BODY></HTML>";
}

// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} 
else {
os.writeBytes(entityBody);
}

private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
 // Construct a 1K buffer to hold bytes on their way to the socket.
 byte[] buffer = new byte[1024];
 int bytes = 0;
 // Copy requested file into the socket's output stream.
 while((bytes = fis.read(buffer)) != -1 ) {
 os.write(buffer, 0, bytes);
 }
}

private static String contentType(String fileName)
  {
    if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
      return "text/html";
    }
    if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
      return "image/jpeg";
    }
    if (fileName.endsWith(".gif")) {
      return "image/gif";
    }
    if (fileName.endsWith(".txt")) {
      return "text/plain";
    }
    if (fileName.endsWith(".pdf")) {
      return "application/pdf";
    }
    return "application/octet-stream";
  }
  

может кто-нибудь, пожалуйста, помочь мне понять, что не так с моим кодом. Я был бы очень признателен за помощь.

Комментарии:

1. У вас есть код, плавающий в середине нигде

2. Пожалуйста, предоставьте минимальное воспроизведение вашего кода

3. Взгляните на это

Ответ №1:

может кто-нибудь, пожалуйста, помочь мне понять, что не так с моим кодом.

Начиная со строки комментария

 // Extract the filename from the request line.
  

у вас есть куча инструкций, а затем объявления методов, которых нет ни в одном class . Это не законная Java.

Если они должны находиться внутри класса (например, вашего HttpRequest класса или WebServer class), то вы, вероятно, допустили ошибку при открытии / закрытии скобок дальше по файлу.

Если нет… тогда вы неправильно понимаете Java. Весь исполняемый код на Java должен быть объявлен внутри класса (или интерфейса, или перечисления).

Ответ №2:

Вы неправильно расставляете некоторые фигурные скобки.

 import java.io.*;
import java.net.*;
import java.util.*;

public final class WebServer {
    public static void main(String argv[]) throws Exception {
        // Set the port number.
        int port = 6789;

        // Establish the listen socket.
        ServerSocket listenSocket = new ServerSocket(port);

        // Process HTTP service requests in an infinite loop
        while (true) {
            // Listen for a TCP connection request
            Socket connectionSocket = listenSocket.accept();

            // Construct an object to process the HTTP request message
            HttpRequest request = new HttpRequest(connectionSocket);

            // Create a new thread to process the request.
            Thread thread = new Thread(request);

            // Start the thread.
            thread.start();
        }

    }
}

final class HttpRequest implements Runnable {
    final static String CRLF = "rn";
    Socket socket;

    // Constructor
    public HttpRequest(Socket socket) throws Exception {
        this.socket = socket;
    }

    // Implement the run() method of the Runnable interface.
    public void run() {
        try {
            processRequest();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void processRequest() throws Exception {
        // Get a reference to the socket's input and output streams.
        InputStream is = socket.getInputStream();
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());

        // Set up input stream filters.
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        // Get the request line of the HTTP request message.
        String requestLine = br.readLine();

        // Display the request line.
        System.out.println();
        System.out.println(requestLine);

        // Get and display the header lines.
        String headerLine = null;
        while ((headerLine = br.readLine()).length() != 0) {
            System.out.println(headerLine);
        }
        // Close streams and socket.
        os.close();
        br.close();
        socket.close();
        // } // *** DELETED
        // } // *** DELETED

        // Extract the filename from the request line.
        StringTokenizer tokens = new StringTokenizer(requestLine);
        tokens.nextToken(); // skip over the method, which should be "GET"
        String fileName = tokens.nextToken();

        // Prepend a "." so that file request is within the current directory.
        fileName = "."   fileName;

        // Open the requested file.
        FileInputStream fis = null;
        boolean fileExists = true;
        try {
            fis = new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            fileExists = false;
        }

        // Construct the response message.
        String statusLine = null;
        String contentTypeLine = null;
        String entityBody = null;
        if (fileExists) {
            statusLine = "HTTP/1.0 200 OK"   CRLF;
            contentTypeLine = "Content-type: "   contentType(fileName)   CRLF;
        } else {
            statusLine = "HTTP/1.0 404 Not Found"   CRLF;
            contentTypeLine = "Content-type: "   "text/html"   CRLF;
            entityBody = "<HTML>"  
                "<HEAD><TITLE>Not Found</TITLE></HEAD>"  
                "<BODY>Not Found</BODY></HTML>";
        }

        // Send the status line.
        os.writeBytes(statusLine);
        // Send the content type line.
        os.writeBytes(contentTypeLine);
        // Send a blank line to indicate the end of the header lines.
        os.writeBytes(CRLF);
        // Send the entity body.
        if (fileExists) {
            sendBytes(fis, os);
            fis.close();
        } else {
            os.writeBytes(entityBody);
        }
    } // *** INSERTED

    private static void sendBytes(FileInputStream fis, OutputStream os)
        throws Exception {
        // Construct a 1K buffer to hold bytes on their way to the socket.
        byte[] buffer = new byte[1024];
        int bytes = 0;
        // Copy requested file into the socket's output stream.
        while ((bytes = fis.read(buffer)) != -1) {
            os.write(buffer, 0, bytes);
        }
    }

    private static String contentType(String fileName) {
        if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
            return "text/html";
        }
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        }
        if (fileName.endsWith(".gif")) {
            return "image/gif";
        }
        if (fileName.endsWith(".txt")) {
            return "text/plain";
        }
        if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        }
        return "application/octet-stream";
    }
} // *** INSERTED