Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HTTP Php服务器_Java_Php_Swing_Webserver - Fatal编程技术网

Java HTTP Php服务器

Java HTTP Php服务器,java,php,swing,webserver,Java,Php,Swing,Webserver,我有一个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.

我有一个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);
        }
    }
}
包装地雷;
导入java.util.*;
导入javax.swing.*;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.*;
导入java.net。*;
公共班机{
私有静态ServerSocket ServerSocket;
公共静态void main(字符串[]args)引发IOException{
JFrame ip=新的JFrame();
JTextField=新的JTextField();
field.setText(“http://“+getIP()+”:8080”);
字段设置为可编辑(false);
场地立根(10,10,380,110);
ip.add(字段);
JButton shutdown=新JButton(“shutdown Minet”);
停堆。立根(30、120、340、50);
ip.add(关机);
ip.setLocationRelativeTo(空);
ip设置大小(400200);
ip.setLayout(空);
ip.setVisible(真);
shutdown.addActionListener(新建ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
System.out.println(“关闭Minet…”);
field.setText(“关闭Minet…”);
setTimeout(()->System.exit(0),1000);
}
});
serverSocket=newserversocket(8080);//开始,在端口8080上侦听
while(true){
试一试{
套接字s=serverSocket.accept();//等待客户端连接
新建ClientHandler;//在单独的线程中处理客户端
}捕获(异常x){
系统输出println(x);
}
}
}
公共静态void setTimeout(Runnable Runnable,int delay){
新线程(()->{
试一试{
睡眠(延迟);
runnable.run();
}捕获(例外e){
系统错误println(e);
}
}).start();
}
私有静态字符串getIP(){
//此尝试将提供主机的公共IP地址。
试一试{
URL=新URL(“http://automation.whatismyip.com/n09230945.asp");
BufferedReader in=新的BufferedReader(新的InputStreamReader(url.openStream());
字符串ipAddress=新字符串();
ipAddress=(in.readLine()).trim();
/*
*如果未连接到internet,则上述代码将返回一个空
*字符串,我们可以检查它的长度,如果长度不大于零,则
*我们可以选择局域网IP、本地IP或专用IP
*/
如果(!(ipAddress.length()>0)){
试一试{
InetAddress ip=InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
返回((ip.getHostAddress()).trim());
}捕获(例外情况除外){
返回“错误”;
}
}
System.out.println(“IP地址为:“+ipAddress”);
返回(IP地址);
}捕获(例外e){
//此尝试将提供主机的专用IP。
试一试{
InetAddress ip=InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
返回((ip.getHostAddress()).trim());
}捕获(例外情况除外){
返回“错误”;
}
}
}
}
//ClientHandler读取HTTP请求并响应
类ClientHandler扩展线程{
私有套接字;//从Web服务器接受的套接字
//在构造函数中启动线程
公共ClientHandler(插座s){
插座=s;
start();
}
//读取HTTP请求、响应并关闭连接
公开募捐{
试一试{
//打开与插座的连接
BufferedReader in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
PrintStream out=新的PrintStream(新的BufferedOutputStream(socket.getOutputStream());
//从第一个输入行“GET/filename.html…”读取文件名
//或者,如果不是此格式,则视为未找到文件。
字符串s=in.readLine();
System.out.println;//记录请求
//尝试为文件提供服务。捕获FileNotFoundException和
//返回HTTP错误“404未找到”。处理无效请求
//同样的方式。
字符串filename=“”;
StringTokenizer st=新的StringTokenizer;
试一试{
//从GET命令解析文件名
if(st.hasMoreElements()&&st.nextToken().equalsIgnoreCase(“GET”)&&st.hasMoreElements())
filename=st.nextToken();
其他的
抛出新的FileNotFoundException();//请求错误
//在尾随“/”后面附加“index.html”
if(filename.endsWith(“/”)
文件名+=“index.html”;
//从文件名中删除前导/后导
while(filename.indexOf(“/”)==0)
filename=filename.substring(1);
//对于基于PC的服务器,将路径中的“/”替换为“\”
filename=filename.replace('/',File.separator.charAt(0));
//检查非法字符以防止访问超级目录
如果(filename.indexOf(“..”)>=0 | | filename.indexOf(':')>=0 | | filename.indexOf('.')>=0)
抛出新的FileNotFoundException();
//如果请求了一个目录,但缺少尾随/号,
//向客户端发送一个HTTP请求以附加它。(这是
//相关链接在客户端中正常工作所必需的)。
$ cd path/to/built-in/php/web/server
$ php -S localhost:8000