Java -客户机-服务器程序- http响应



我是编码和Java的新手,我创建了一个简单的客户机-服务器程序,客户机可以在其中请求文件。它的内容将与数据类型和长度等细节一起显示在浏览器页面中。我现在有一个问题,我不知道如何在浏览器中显示正确连接的服务器响应,如"HTTP/1.1 200 ok";对于已关闭的连接,如"connection: close"。我有一个方法来处理响应,如下所示:

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+"rn");
out.println("Content-Length: " +length+"rn");

}


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" +"rn");              
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" +"rn");                                     
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);
}
}
}

有什么建议吗?谢谢你

如果您试图重新发明实现请求/响应通信的轮子,则会使您的方式过于复杂。最好使用Spring MVC。

最新更新