【问题标题】:Java HTTP Php ServerJava HTTP PHP 服务器
【发布时间】:2018-05-11 16:12:33
【问题描述】:

我有一个 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 不喜欢那么多代码...这就是为什么我有这个外部链接...)

【问题讨论】:

  • 实际上 StackOverflow 更喜欢有问题的相关代码而不是外部链接,因为外部链接可能会失效,从而使问题在未来无法使用
  • 我看到了您的评论 - 但外部链接并不是特别有用,就像我们想测试代码等一样,它使直接从站点复制/粘贴变得更容易。可能不是专门针对这个问题的,只是仅供参考。
  • 好的,谢谢...但是我无法发布问题,因为它说了很多代码...
  • 您的问题具有误导性。 Java和PHP是两种不同的技术,编程语言。如果您解释了您想要做什么,那么也许人们可以为您指明正确的路径。
  • 你到底为什么要在它上面运行 PHP?抛开语言讨论不谈:有 6 个积极开发的支持 PHP 的网络服务器,它们可以更好地完成任何你能想到的事情

标签: java php swing webserver


【解决方案1】:

我无法确定您面临的确切问题。但是,根据问题,您似乎希望在 JAVA 服务器旁边安装 PHP 服务器。

这很容易做到,只需在安装 PHP 时选择不同的端口号。默认情况下,任何 PHP 服务器都选择端口 80,因此这本身就解决了您的问题。只需安装任何PHP服务器,可以通过http://localhost访问,而您的java服务器可以通过http://localhost:8080访问。

here 也有类似的讨论。请检查一下。

【讨论】:

  • 我有一个由 Java 托管的本地网络服务器,并且在那个确切的网络服务器上我希望能够运行 php 文件...
  • 这正是我在回复中提到的
  • @Penguine 我读到这个问题的方式是他想让他写的 Java 服务器执行 PHP 代码
  • @Penguine 取决于,你可以让 Java 调用 PHP-CLI,但这是一个可怕的 hack
  • @JeroenSteenbeeke 是的 PHP-CLI 可以解决问题……但正如你所说……这是一个可怕的黑客攻击。我仍然认为最好的方法是在同一台服务器(不同的端口)上进行 java PHP-API 调用。
【解决方案2】:

根据您的问题,我了解到您曾经使用 PHP 作为 Web 编程语言。并且您想用 Java 制作一个显示 PHP Web Server 的一些页面的应用程序。

为此,我认为您需要在您的应用程序中包含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 的一部分。

【讨论】:

  • 谢谢!我可以使用端口 80 或 143 吗?
  • 如何安装 php?
猜你喜欢
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 2011-08-27
  • 2023-03-29
  • 2021-04-14
  • 2018-07-05
  • 2020-03-23
相关资源
最近更新 更多