【问题标题】:Java - Client-server program - http responseJava - 客户端-服务器程序 - http 响应
【发布时间】:2021-10-07 14:42:03
【问题描述】:

我是编码和 Java 的新手,我创建了一个简单的客户端-服务器程序,客户端可以在其中请求文件。它的内容将与数据类型和长度等一些详细信息一起显示在浏览器页面中。 我现在遇到了一个问题,我不确定如何在浏览器中显示服务器对正确连接(如“HTTP/1.1 200 OK”)和关闭连接(如“连接:关闭”)的响应。 我有一个方法来处理响应如下:

import java.io.*;
import java.net.*;
import java.util.*;
public class ReadRequest {

    private final static int LISTENING_PORT = 50505;
    protected static Socket client;
    protected static PrintStream out;
    static String requestedFile;


    
    @SuppressWarnings("resource")
    public static void main(String[] args) {    
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(LISTENING_PORT);
        }
        catch (Exception e) {
            System.out.println("Failed to create listening socket.");
            return;
        }
        System.out.println("Listening on port " + LISTENING_PORT);

        try {
            while (true) {
                Socket connection = serverSocket.accept();
                System.out.println("\nConnection from "+ connection.getRemoteSocketAddress());
                ConnectionThread thread = new ConnectionThread(connection);
                thread.start();
            }
        }
        catch (Exception e) {
            System.out.println("Server socket shut down unexpectedly!");
            System.out.println("Error: " + e);
            System.out.println("Exiting.");
        }
    }
    

    private static void handleConnection(Socket connection) {

        String username = System.getProperty("user.name");
        String httpRootDir = "C:\\Users\\"+(username)+"\\Downloads\\";
        client = connection;
        try {
            
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintStream (client.getOutputStream());

            String line = null;     
            String req = null;      

            
            req = in.readLine();
            
            line = req;
            while (line.length() > 0)
            {
                line = in.readLine();
            }
            
            StringTokenizer st = new StringTokenizer(req);

            if (!st.nextToken().equals("GET"))
            {                                      
            
                sendErrorResponse(501);                                       
                return;
            }

            
            requestedFile = st.nextToken();

            File f = new File(httpRootDir + requestedFile);

    
            if (!f.canRead())
            {
                
                sendErrorResponse(404);                                       
                return;
            }
            
            sendResponseHeader(getMimeType(requestedFile),(int) f.length());
            
            sendFile(f,client.getOutputStream());

        }
        catch (Exception e) {
            System.out.println("Error while communicating with client: " + e);
        }
        finally {  
            try {
                connection.close();
            }
            catch (Exception e) {
            }
            System.out.println("Connection closed.");
        };
    }
    

    private static void sendResponseHeader(String type,int length)
    {
           
          out.println("Content-type: " +type+"\r\n");
          out.println("Content-Length: " +length+"\r\n");
 
    }
    
    
    private static void sendErrorResponse(int errorCode)
    {
        switch(errorCode) {
        case 404:
            out.print("HTTP/1.1 404 Not Found");    
            out.println("Connection: close " ); 
            out.println("Content-type: text/plain" +"\r\n");              
            out.println("<html><head><title>Error</title></head><body> <h2>Error: 404 Not Found</h2> <p>The resource that you requested does not exist on this server.</p> </body></html>");
            break;
        case 501:
            out.print("HTTP/1.1 501 Not Implemented");    
            out.println("Connection: close " ); 
            out.println("Content-type: text/plain" +"\r\n");                                     
            break;
        }                               
    }


    private static String getMimeType(String fileName) {
        int pos = fileName.lastIndexOf('.');
        if (pos < 0)  
            return "g-application/x-unknown";
        String ext = fileName.substring(pos+1).toLowerCase();
        if (ext.equals("txt")) return "text/plain";
        else if (ext.equals("html")) return "text/html";
        else if (ext.equals("htm")) return "text/html";
        else if (ext.equals("css")) return "text/css";
        else if (ext.equals("js")) return "text/javascript";
        else if (ext.equals("java")) return "text/x-java";
        else if (ext.equals("jpeg")) return "image/jpeg";
        else if (ext.equals("jpg")) return "image/jpeg";
        else if (ext.equals("png")) return "image/png";
        else if (ext.equals("gif")) return "image/gif";
        else if (ext.equals("ico")) return "image/x-icon";
        else if (ext.equals("class")) return "application/java-vm";
        else if (ext.equals("jar")) return "application/java-archive";
        else if (ext.equals("zip")) return "application/zip";
        else if (ext.equals("xml")) return "application/xml";
        else if (ext.equals("xhtml")) return"application/xhtml+xml";
        else return "g-application/x-unknown";
        
    }

    
    private static void sendFile(File file, OutputStream socketOut) throws IOException {
        try (InputStream infile = new BufferedInputStream(new FileInputStream(file))) {
            OutputStream outfile = new BufferedOutputStream(socketOut);
            while (true) {
                int x = infile.read(); 
                if (x < 0)
                    break; 
                outfile.write(x);  
            }
            outfile.flush();
        }
    }
    
    private static class ConnectionThread extends Thread {
        Socket connection;
        ConnectionThread(Socket connection) {
            this.connection = connection;
        }
        public void run() {
            handleConnection(connection);
        }
    }
}

关于我如何做到这一点的任何建议?谢谢

【问题讨论】:

  • 你能分享你剩下的代码吗?你在做什么以及你想用这段代码实现什么并不是很明显。
  • 已更新其余代码
  • 也许你应该看看这个stackoverflow.com/questions/10788125/…
  • 谢谢,我可以像链接中建议的那样打印我的文字,我的意思是,要获取连接的状态码(http),比如200,不应该有我的方法可以用吗?

标签: java http client-server


【解决方案1】:

如果您尝试重新发明轮子来实现请求/响应通信,那么您的方法就太复杂了。最好只使用 Spring MVC。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多