gpt4 book ai didi

Java HTTP PHP 服务器

转载 作者:行者123 更新时间:2023-12-02 08:36:39 25 4
gpt4 key购买 nike

我有一个 Java 应用程序,可以在端口 8080 上创建本地 HTTP Web 服务器。有什么可能的方法可以在其上使用/安装 Php 吗?我在谷歌上搜索了这一点,但找不到任何帮助......任何帮助表示赞赏!

到目前为止我的代码:

package minet;

import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;

public class main {
private static ServerSocket serverSocket;

public static void main(String[] args) throws IOException {
JFrame ip = new JFrame();
JTextField field = new JTextField();
field.setText("http://" + getIP() + ":8080");
field.setEditable(false);
field.setBounds(10, 10, 380, 110);
ip.add(field);
JButton shutdown = new JButton("Shutdown Minet");
shutdown.setBounds(30, 120, 340, 50);
ip.add(shutdown);
ip.setLocationRelativeTo(null);
ip.setSize(400, 200);
ip.setLayout(null);
ip.setVisible(true);
shutdown.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Shutting down Minet...");
field.setText("Shutting down Minet...");
setTimeout(() -> System.exit(0), 1000);
}
});

serverSocket = new ServerSocket(8080); // Start, listen on port 8080
while (true) {
try {
Socket s = serverSocket.accept(); // Wait for a client to connect
new ClientHandler(s); // Handle the client in a separate thread
} catch (Exception x) {
System.out.println(x);
}
}
}

public static void setTimeout(Runnable runnable, int delay) {
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
} catch (Exception e) {
System.err.println(e);
}
}).start();
}

private static String getIP() {
// This try will give the Public IP Address of the Host.
try {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = new String();
ipAddress = (in.readLine()).trim();
/*
* IF not connected to internet, then the above code will return one empty
* String, we can check it's length and if length is not greater than zero, then
* we can go for LAN IP or Local IP or PRIVATE IP
*/
if (!(ipAddress.length() > 0)) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
System.out.println("IP Address is : " + ipAddress);

return (ipAddress);
} catch (Exception e) {
// This try will give the Private IP of the Host.
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
}
}

// A ClientHandler reads an HTTP request and responds
class ClientHandler extends Thread {
private Socket socket; // The accepted socket from the Webserver

// Start the thread in the constructor
public ClientHandler(Socket s) {
socket = s;
start();
}

// Read the HTTP request, respond, and close the connection
public void run() {
try {

// Open connections to the socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));

// Read filename from first input line "GET /filename.html ..."
// or if not in this format, treat as a file not found.
String s = in.readLine();
System.out.println(s); // Log the request

// Attempt to serve the file. Catch FileNotFoundException and
// return an HTTP error "404 Not Found". Treat invalid requests
// the same way.
String filename = "";
StringTokenizer st = new StringTokenizer(s);
try {

// Parse the filename from the GET command
if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements())
filename = st.nextToken();
else
throw new FileNotFoundException(); // Bad request

// Append trailing "/" with "index.html"
if (filename.endsWith("/"))
filename += "index.html";

// Remove leading / from filename
while (filename.indexOf("/") == 0)
filename = filename.substring(1);

// Replace "/" with "\" in path for PC-based servers
filename = filename.replace('/', File.separator.charAt(0));

// Check for illegal characters to prevent access to superdirectories
if (filename.indexOf("..") >= 0 || filename.indexOf(':') >= 0 || filename.indexOf('|') >= 0)
throw new FileNotFoundException();

// If a directory is requested and the trailing / is missing,
// send the client an HTTP request to append it. (This is
// necessary for relative links to work correctly in the client).
if (new File(filename).isDirectory()) {
filename = filename.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n" + "Location: /" + filename + "/\r\n\r\n");
out.close();
return;
}

// Open the file (may throw FileNotFoundException)
InputStream f = new FileInputStream(filename);

// Determine the MIME type and print HTTP header
String mimeType = "text/plain";
if (filename.endsWith(".html") || filename.endsWith(".htm"))
mimeType = "text/html";
else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
mimeType = "image/jpeg";
else if (filename.endsWith(".gif"))
mimeType = "image/gif";
else if (filename.endsWith(".class"))
mimeType = "application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n" + "Content-type: " + mimeType + "\r\n\r\n");

// Send file contents to client, then close the connection
byte[] a = new byte[4096];
int n;
while ((n = f.read(a)) > 0)
out.write(a, 0, n);
out.close();
} catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n" + "Content-type: text/html\r\n\r\n"
+ "<html><head></head><body>" + filename + " not found</body></html>\n");
out.close();
}
} catch (IOException x) {
System.out.println(x);
}
}
}

(Stackoverflow 不喜欢那么多代码...这就是为什么我有这个外部链接...)

最佳答案

从你的问题中我了解到你曾经使用PHP作为网络编程语言。您想要用 Java 创建一个应用程序来显示来自 PHP Web 服务器的一些页面。

为此,我认为您需要包括 Built-in web server在您的应用程序中。您只需要download it ,将其解压缩到您的应用程序路径或任何您想要的位置。您可以在该目录中找到INSTALL文件。如图所示安装它,然后通过以下方式启动 Web 服务器:

$ cd path/to/built-in/php/web/server
$ php -S localhost:8000

执行cmd命令如this post所示。您可以根据需要更改端口号。

另一种变体是,您需要在应用程序安装包中包含压缩的 Apache 和 PHP,然后将其解压缩,并以编程方式编辑配置文件,然后将应用程序安装到某些计算机上。

要显示来自 PHP Web 服务器的页面,您只需使用 WebViewhere 显示了如何在 Swing 中使用它的示例。或者如果您愿意,您可以直接使用 JavaFX,而不使用 Swing,因为 WebView 是 JavaFX 的一部分。

关于Java HTTP PHP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com